Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Seven prefixes own our login redirect now, and every other unknown URL finally gets a 404

Ten days ago I threw thirty malformed URLs at our own site and wrote down the answers. One of them was a real bug: nakodo.app/nope did not reach our 404 page. It answered 307 to /login?next=%2Fnope. I published that wit

Ten days ago I threw thirty malformed URLs at our own site and wrote down the answers. One of them was a real bug: nakodo.app/nope did not reach our 404 page. It answered 307 to /login?next=%2Fnope.

I published that with a sentence about what I would do next:

The fix I am going with is to send an unknown path to the 404 instead of the login page, which means naming the private prefixes rather than inferring them. [...] The reason that is not a one-line change is the thing I like about writing this down: moving from "deny unless public" to "deny if private" means every future private route has to remember to join that list, and the test that would catch a forgotten one has to be written before the switch, not after.

That change is now deployed. This is what it took, and the one thing it broke that I did not expect.

What the boundary used to say

Nakodo is a web app with a large public side: guides, calculators, comparison pages, 106 URLs in the sitemap. The session check runs in src/proxy.ts, which is what Next 16 calls the file that used to be middleware.ts. It was one condition:

const { data } = await supabase.auth.getClaims();
const path = request.nextUrl.pathname;
if (!data?.claims && !isPublicPath(path)) {
  // redirect to /login?next=<path>
}

Read that as English and the bug is obvious: "if you are signed out and this path is not on the public list, you need to log in." A path nobody has ever defined is not on the public list. Neither is a typo. Neither is a stale inbound link from three months ago. All of them got handed the login page.

Default deny is the right instinct for an auth boundary, and it is why the code was written that way. The cost is that "private" and "does not exist" become the same answer, and the one that suffers is the 404 page, which stops being reachable except inside a prefix that is already public.

Why it was safe to invert

The thing that made this a change I was willing to make is in the comment above the proxy:

Pages still check the user themselves; this is only the first, optimistic check.

There are 22 files under src/app that call requireUser or requireAdmin, and every page and action in the app is behind one of them. The proxy is a courtesy: it refreshes the Supabase session cookie and saves a signed-out visitor from loading a page that would have bounced them anyway. It is not the thing that protects anything.

If the proxy had been the only check, inverting the default would have been a security change, and I would not have done it in a commit that also added thirty content pages. Because it is the second lock on a door that is already locked, the question was only ever "does a signed-out visitor get a useful answer".

The new rule is two lists, not one

// Where robots.txt sends crawlers away from: the signed-in app. The auth pages
// are left crawlable so crawlers can see their noindex tag.
export const PRIVATE_PREFIXES = ["/campaigns", "/settings", "/onboarding", "/billing", "/api/"];

// Where a signed-out visitor is sent to /login. Anything else that isn't public
// is left to Next, so a mistyped or made-up address is a 404 rather than a
// redirect to the login page, which crawlers would otherwise keep following.
const APP_PREFIXES = [...PRIVATE_PREFIXES, "/support", "/admin"];

export function needsSession(path: string): boolean {
  return !isPublicPath(path) && APP_PREFIXES.some((p) => path === p.replace(/\/$/, "") || path.startsWith(p.endsWith("/") ? p : `${p}/`));
}

PRIVATE_PREFIXES already existed, because robots.txt is generated from it. Reusing it was tempting and wrong, so APP_PREFIXES extends it by two. /support and /admin are app pages that need a session, but they are not pages a crawler needs to be steered away from: nothing public links to either, so there is nothing to crawl. Two lists with different jobs, differing by two entries, with the reason written above each.

The matching is the fiddly part, and both halves of it earn their place:

  • path === p.replace(/\/$/, "") makes /api on its own match the /api/ prefix. Without it, the one path in the list written with a trailing slash would have a hole at its own root.
  • path.startsWith(p.endsWith("/") ? p :${p}/) appends the slash that is missing. Without it, /campaignsx starts with /campaigns and a public page named /campaignsx could never exist.

Neither of those is clever. Both are the kind of thing that is correct the day you write it and wrong six months later when somebody adds a prefix in the other style, which is why they are tested.

The test, written before the switch

test("only app pages send signed-out visitors to /login", () => {
  for (const path of ["/campaigns", "/campaigns/abc", "/settings/plan", "/admin/runs", "/support", "/onboarding", "/api/x"]) {
    assert.ok(needsSession(path), `${path} should redirect to /login`);
  }
  for (const path of ["/blogBlog", "/index", "/guidesx", "/campaignsx", "/guides/how-to-find-youtube-influencers"]) {
    assert.ok(!needsSession(path), `${path} should not redirect to /login`);
  }
});

The second loop is the whole point of the commit. /campaignsx is there because of the slash rule above. /blogBlog and /guidesx are there because they are the two shapes a real broken link takes: somebody's CMS concatenated a label onto a path, or a character got lost off the end. /index is there because crawlers try it unprompted.

The test suite went from 623 tests to 732 in that commit. Exactly one of the 109 new ones was written by hand, and it is this one. The other 108 are generated, four per content page, which is a different post.

What the deployed site answers now

Every line reproducible against the live site:

$ for u in /campaigns /support /admin/runs /guidesx /blogBlog /nope /tools; do
>   printf '%-14s ' "$u"
>   curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' "https://nakodo.app$u"
> done
/campaigns      307 https://nakodo.app/login?next=%2Fcampaigns
/support        307 https://nakodo.app/login?next=%2Fsupport
/admin/runs     307 https://nakodo.app/login?next=%2Fadmin%2Fruns
/guidesx        404
/blogBlog       404
/nope           404
/tools          200

The headers say something the status code does not:

$ curl -sI https://nakodo.app/guidesx | grep -iE 'x-matched-path|x-vercel-cache|age'
age: 7135
x-matched-path: /404
x-vercel-cache: HIT

A made-up URL is now answered by a prerendered page sitting in the CDN, nearly two hours old at the time I ran that. The redirect it used to get had no cache status at all, because a redirect built from a session check cannot be cached. So the change did not only fix what crawlers see, it moved the most-requested path shape on any website, the wrong one, off the function and onto the edge.

/nope is worth opening rather than curling. Our 404 is a field guide entry for a bird that was never recorded, and until this week you could only find it by mistyping a path inside a prefix that already existed.

The thing it broke: a test message that now lies

The allowlist has its own test, and it is the one that catches a public page nobody allowlisted:

test("every page in the sitemap is open to signed-out visitors", () => {
  for (const path of [...STATIC_PAGES.map((p) => p.path), ...ENTRIES.map((e) => e.path)]) {
    assert.ok(isPublicPath(path), `${path} would redirect crawlers to /login`);
  }
});

I deleted two lines from the allowlist in a scratch worktree to watch it fail, and it failed correctly:

✖ every page in the sitemap is open to signed-out visitors
  AssertionError: /features would redirect crawlers to /login

Except that it would not, any more. A sitemap page missing from the allowlist is no longer a redirect to the login page. It is a 404, for everyone, signed in included, because nothing in APP_PREFIXES matches it either. The failure is still a failure, and it is now a worse one than the message claims: a page in your sitemap that answers 404 is the single clearest instruction you can give a search engine to forget about it.

That is the part of this change I would not have found by reading the diff. Inverting a default does not only change behaviour, it silently re-points every sentence anybody wrote about the old behaviour, including the sentences inside assertions. The message is two words wrong and the test is still green, so nothing will ever tell me.

The message wants to read would be a 404 for everyone, and that is a one-string change I am making next. The only reason I know to make it is that I broke the test on purpose to read what it said, which is not a habit I had before this week and now is.

If you want to check your own

The loop at the top of the earlier post is the whole method, and the one request that matters is a path that does not exist and is not inside any public prefix. Something like /qqq. If that gets you a redirect to a sign-in page, your 404 is unreachable from the outside and your soft-404 report in Search Console is going to keep growing. The fix is to stop asking "is this public" and start asking "is this mine".

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.