DEV Community

Daniel Pertu
Daniel Pertu

Posted on

A readable cookie mirrors our httpOnly session, so a static page can offer My account

Most of our traffic lands on a public page: a provider page, a test-format page, an employer guide. Those pages are statically rendered, and every one of them ends in a "Sign Up" button.

If you already have an account, that button is wrong. It is not broken, you end up in the right place eventually, but offering sign-up to someone who signed up last week is the kind of small wrongness that makes a product feel like it is not paying attention.

The obvious fix is not available. Supabase's session cookies are httpOnly, so the page's own JavaScript cannot see them, and that is the correct setting for a session cookie. The other obvious fix is to ask the server, and that puts an auth round trip behind a page view whose whole point is that it is cached HTML.

So the middleware mirrors one bit.

Presence, not identity

/**
 * Whether any of these cookies is a Supabase session cookie:
 * `sb-<project>-auth-token`, or one of its `.0`, `.1` chunks when the session
 * is too large for a single cookie. The PKCE `-code-verifier` cookie set during
 * an OAuth round trip is not a session and is excluded.
 */
export function hasSessionCookie(cookies: { name: string; value: string }[]): boolean {
  return cookies.some(
    ({ name, value }) =>
      value !== '' && name.startsWith('sb-') && /-auth-token(\.\d+)?$/.test(name)
  );
}
Enter fullscreen mode Exit fullscreen mode

Three details in one predicate, and all three came from reading what is actually in a browser mid-flow rather than from the docs. A large session is chunked across .0 and .1, so an exact name match misses it. An empty value is a cookie being cleared, not a session. And during an OAuth round trip there is a sb-<project>-auth-token-code-verifier cookie that matches a naive prefix test and means the opposite of signed in: it is there precisely because sign-in has not finished. The test file is five assertions long and four of them are that last group:

it('ignores the PKCE verifier, empty values and unrelated cookies', () => {
  expect(hasSessionCookie([c('sb-abc-auth-token-code-verifier')])).toBe(false);
  expect(hasSessionCookie([c('sb-abc-auth-token', '')])).toBe(false);
  expect(hasSessionCookie([c('cp_country'), c('device_token')])).toBe(false);
  expect(hasSessionCookie([])).toBe(false);
});
Enter fullscreen mode Exit fullscreen mode

The proxy then copies that boolean into a cookie the page can read:

function syncSignedInHint(response: NextResponse, request: NextRequest): NextResponse {
  const signedIn = hasSessionCookie(request.cookies.getAll());
  const current = request.cookies.get(SIGNED_IN_HINT_COOKIE)?.value === '1';
  if (signedIn === current) return response;

  response.cookies.set(SIGNED_IN_HINT_COOKIE, signedIn ? '1' : '', {
    ...LONG_LIVED_COOKIE_OPTIONS,
    httpOnly: false,
    maxAge: signedIn ? LONG_LIVED_COOKIE_OPTIONS.maxAge : 0,
  });
  return response;
}
Enter fullscreen mode Exit fullscreen mode

Two things worth copying there. The early return means a steady-state visitor gets no Set-Cookie at all: the write only happens on the transition, in either direction. And the clear path sets an empty value with maxAge: 0 rather than writing 0, so a stale cookie is deleted rather than left as a falsy string that some future reader forgets to parse.

It also deliberately makes no Supabase call. The middleware does talk to Supabase on protected routes, but not for this, because the entire value of the hint is that it costs nothing on the pages that have no session to validate.

It is a hint, and it is allowed to be wrong

The doc comment is the part I would push hardest in review:

 * It is a hint, never an authorisation: the cookie says nothing about whether
 * the session is still valid, and holds no identifier. The worst a stale or
 * forged value can do is show "My account" to someone who is then asked to
 * sign in by the page it links to.
Enter fullscreen mode Exit fullscreen mode

That is the property that makes the whole thing cheap. The cookie carries 1 or nothing. It is not signed, because there is nothing to protect: forging it buys you a different label on a link. Every protected route still resolves the real session server-side, exactly as before, and a visitor who tampers with the flag gets sent to the sign-in page by the destination.

I have written the opposite kind of cookie in this codebase, and the difference is the test I now apply before making one readable: if the worst outcome of a forged value is a wrong word on a button, it can be readable. If the worst outcome is access, it cannot be a cookie at all.

Reading it without a hydration mismatch

// Cookies have no change event. The value only changes across a navigation,
// which re-renders the components reading it, so there is nothing to subscribe to.
const subscribe = () => () => {};

export function useSignedInHint(): boolean {
  return useSyncExternalStore(subscribe, readHint, () => false);
}
Enter fullscreen mode Exit fullscreen mode

useSyncExternalStore is doing something slightly off-label here. There is no store and no subscription: the third argument, the server snapshot, is the whole reason it is used. It returns false on the server and during hydration, so statically rendered HTML always contains the signed-out markup and React swaps after mount without complaining. A useEffect plus useState gets you the same two renders with more lines and a flash of the wrong branch inside the same commit.

I counted hook usage across the app ten days ago and found zero useSyncExternalStore calls. There are now two, and the other one is the same trick for a different question: a phone sticky bar that only exists after hydration uses useSyncExternalStore(noSubscribe, () => true, () => false) as an "am I on the client" flag. Once you have seen the three-argument form as a server-versus-client switch, it turns up everywhere.

The component on top is small enough to quote whole:

export function AccountAwareLink({ href, children, signedInHref = ACCOUNT_HREF, signedInChildren, ...rest }: AccountAwareLinkProps) {
  const signedIn = useSignedInHint();
  return (
    <Link {...rest} href={signedIn ? signedInHref : href}>
      {signedIn ? signedInChildren : children}
    </Link>
  );
}

/** Renders its children only for a visitor who does not look signed in. */
export function SignedOutOnly({ children }: { children: ReactNode }) {
  return useSignedInHint() ? null : children;
}
Enter fullscreen mode Exit fullscreen mode

Eight usages across five files: the public header, the public footer, the landing page, and the two interactive demos on it. It extends ComponentProps<typeof Link>, which matters because most of those call sites sit inside <Button asChild>, and the props the Radix Slot merges in have to pass straight through to the underlying Link.

See it

Fetch any public page signed out and look at the response headers:

curl -sD - -o /dev/null https://cogniprep.app/login
Enter fullscreen mode Exit fullscreen mode

The only cookie we set is cp_country. No hint cookie, because for a signed-out visitor with no hint cookie there is no transition to record, which is the early return above doing its job on the most common request we serve.

Then view the source of cogniprep.app. The rendered text contains "Sign Up" twice and "My account" zero times, so a crawler and a first-time visitor see the same thing. Search the raw HTML for signedInChildren and you will find it once, inside the React payload:

"href":"/signup","signedInChildren":"My account","children":"Sign Up"
Enter fullscreen mode Exit fullscreen mode

Both branches ship, the server picks the signed-out one, and the client decides on the basis of one character in a cookie it is explicitly not allowed to trust for anything else. If you want to watch the swap, sign in at cogniprep.app/login and come back to the homepage: the header button says "My account" and the page is still the same cached HTML it was before.

Top comments (0)