Skip to content
Felipe Reducino
All posts

Your access token doesn't belong in the browser

How I used Next.js Route Handlers as a BFF to run OAuth 2.0 + PKCE, keep every token on the server, and let http-only cookies do the rest.

Felipe Reducino

Implementing OAuth in a frontend app usually starts with one question: which flow should I use? Today the answer is well known: Authorization Code with PKCE.

But there's a second question that gets much less attention, and I think it matters more:

Once the tokens come back, where do they live?

The problem: if JavaScript can read it, so can an attacker

The most common answers are localStorage, sessionStorage or a variable in memory (a React context, a store). They all share the same weakness: any script running on your page can read them.

That includes an XSS vulnerability, a compromised npm dependency or a third-party script you added for analytics. You don't need to be careless for this to happen. You only need one bad line of code anywhere in your bundle.

And an access token, once stolen, works from anywhere until it expires. A refresh token is worse: it keeps minting new access tokens for days.

What PKCE solves (and what it doesn't)

PKCE (Proof Key for Code Exchange) protects one specific moment: when the authorization code is traded for tokens.

  • The client creates a random secret, the code verifier.

  • It sends a hash of it, the code challenge, when redirecting the user to sign in.

  • When it trades the code for tokens, it sends the original verifier, and the server checks that it matches the challenge.

If someone intercepts the code, it's useless without the verifier.

That's a real protection, and you should always use it. But notice what it doesn't cover: PKCE protects the exchange, not the storage. After the exchange, the tokens still have to live somewhere, and PKCE has no opinion about where.

The idea: a Backend for Frontend (BFF)

The BFF pattern changes who holds the tokens. Instead of the browser, a small server layer that belongs to your frontend keeps them:

Browser  ──(same origin, cookies)──▶  BFF  ──(Bearer token)──▶  APIs
  • The browser only talks to its own origin.

  • The BFF receives the tokens, stores them in http-only cookies, and attaches them to API calls on the server.

  • The page knows that the user is signed in. It never knows with what.

This isn't a niche idea. The IETF guidance for OAuth in browser-based apps describes the BFF as the most secure option for this kind of application, because the tokens are never exposed to the browser at all.

Why Next.js makes this easy

A BFF used to mean deploying and maintaining a separate service. With Next.js, you already have a server in the same project, on the same origin and in the same deployment:

  • Route Handlers (app/api/*/route.ts) are the BFF endpoints.

  • The OAuth callback can be a Route Handler too. The code arrives on the server, gets exchanged on the server, and the tokens go straight into a Set-Cookie header. No component ever sees them.

  • Server Components and Server Actions can read the session cookie and call your APIs directly.

  • Environment variables without the NEXT_PUBLIC_ prefix never reach the browser bundle, so even the API's address can stay private.

The whole idea fits in one handler:

// app/api/me/route.ts
export async function GET(request: NextRequest) {
  const token = request.cookies.get("access_token")?.value;
  if (!token) return Response.json({ error: "not signed in" }, { status: 401 });

  return fetch(`${process.env.API_URL}/me`, {
    headers: { Authorization: `Bearer ${token}` },
  });
} 

The browser calls /api/me. The cookie goes along automatically. The token turns into a Bearer header only on the server.

Cookies: the details that matter

Using cookies is only safe if you set them correctly. These are the attributes worth understanding:

  • HttpOnly: the cookie can't be read by document.cookie. This is the main protection.

  • Secure: the cookie is only sent over HTTPS. Watch out in local development: browsers silently drop Secure cookies on plain http://localhost, so make it depend on the environment.

  • SameSite=Lax: the browser won't send the cookie on cross-site POST requests, which is your main CSRF protection. Prefer Lax over Strict for anything the sign-in flow depends on. The OAuth callback is a navigation coming from another site (the identity provider), and Strict cookies aren't sent on it.

  • Max-Age: match each cookie's lifetime to its token's. There's no reason for the cookie to outlive what's inside it.

  • Domain and the cookie name: only set a shared domain if several subdomains really need the same session. If several apps share a domain, give their cookies distinct names so they don't overwrite each other.

The session isn't the only thing that needs cookies. The OAuth flow is a round trip through another site, so some state has to survive it: the PKCE verifier, the state parameter, the page the user wanted to reach. Treat that state as temporary: give it a short lifetime (minutes, not days), clear it on every way out of the callback (including errors), and validate any redirect target before using it.

What the BFF costs you

No pattern is free. Things to keep in mind:

  • Every API call adds a hop through your server. It's usually small, but it isn't zero.

  • CSRF is now your responsibility. Cookies are sent automatically, so a state-changing route needs SameSite, plus a same-origin check (Origin header) or a CSRF token.

  • Refreshing tokens needs care. If your identity provider rotates refresh tokens, two parallel requests refreshing at the same time can look like token theft and end the session. Make sure only one refresh per session runs at a time.

  • Logout has two steps. Revoke the refresh token on the server, then clear the cookies, using the same attributes they were set with. Otherwise the cookie can survive, or the session stays valid on the server.

  • A route guard isn't authorisation. A middleware/proxy that checks "is there a session cookie?" is good for redirects, but your API must still validate the token on every request.

Summary

  • PKCE protects the code exchange. Always use it.

  • Where tokens live is a separate decision, and the browser is the riskiest answer.

  • A BFF keeps tokens on the server. The browser only gets an http-only cookie.

  • Next.js gives you the BFF for free: Route Handlers, server-side callbacks and private environment variables, all in the same project.

  • Cookie attributes matter: HttpOnly, Secure, SameSite=Lax and a Max-Age that matches the token.

  • Know the trade-offs: CSRF, refresh concurrency and proper logout.

The best place to store a secret in the browser is not to store it there at all.

Where are your tokens living today?