VENNStart
Guide

Refresh tokens in the Next.js App Router when parallel requests return 401

httpOnly cookies, refreshing in the proxy before render, one shared refresh promise on the client, and the retry bugs I fixed one at a time.

Lê Anh Tuấn4 min read

An access token expires just as a page sends five requests in parallel, and all five 401s try to refresh. With rotation, the later calls present an already-replaced token and the person is sent to the login page. On a dashboard I fixed it by keeping tokens in cookies and refreshing in the proxy before render. On the client, every refresh in a tab shares one promise. The examples use Next.js 15 or 16 and an API that returns both tokens at login.

Both tokens in httpOnly cookies

The access token is a short-lived JWT (5 to 15 minutes). If the API only checks its signature and expiry, it remains valid until exp. Earlier revocation needs a server-side check. The refresh token lives longer and is revocable, and a leaked one hurts for much longer, so it has to stay away from JavaScript.

Anything injected through XSS can read localStorage, and memory is lost on reload. I keep both tokens in httpOnly, Secure, SameSite=Lax cookies on the Next.js domain. Next.js reads them on the server and calls the API with Authorization: Bearer ...; client requests go through same-origin Route Handlers (a backend-for-frontend, or BFF).

I also never send a token to the client, whether through a JSON endpoint or a Client Component prop. Props are serialized into the RSC payload, and from then on httpOnly protects nothing. I made exactly that mistake in Sosifie's chat.

// lib/session.ts
export const ACCESS_COOKIE = 'access_token'
export const REFRESH_COOKIE = 'refresh_token'

const base = { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax' as const, path: '/' }
export const accessCookie = { ...base, maxAge: 60 * 15 } // same lifetime as the JWT
export const refreshCookie = { ...base, maxAge: 60 * 60 * 24 * 30 }

export type RefreshResult =
  | { status: 'ok'; accessToken: string; refreshToken: string }
  | { status: 'rejected' } // the API said no: end the session
  | { status: 'unavailable' } // timeout or 5xx: keep the session

export async function refreshTokens(refreshToken: string): Promise<RefreshResult> {
  try {
    const res = await fetch(`${process.env.API_URL}/auth/refresh`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken }),
      signal: AbortSignal.timeout(5000),
    })
    if (res.status === 401 || res.status === 403) return { status: 'rejected' }
    if (!res.ok) return { status: 'unavailable' }
    return { status: 'ok', ...(await res.json()) }
  } catch {
    return { status: 'unavailable' }
  }
}

Earlier, any refresh failure ended the session. With three outcomes, only an explicit 401 or 403 clears the cookies; a timeout or 5xx leaves them, because a few seconds of bad network is no reason to sign anyone out.

Refresh in the proxy, because Server Components can't write cookies

In the App Router, the proxy, Server Actions and Route Handlers can write cookies, while Server Components can only read them. My first server version refreshed inside the Server Components' fetch wrapper, so the new tokens were never saved after the backend rotated, and the next request was rejected. The refresh moved to middleware.

Next.js 16 uses proxy.ts (Node.js runtime by default), Next.js 15 uses middleware.ts (Edge by default, Node.js stable since 15.5), and the code below runs on both. The proxy runs on every matched request, prefetches included, so it reads exp locally (60 seconds of slack) and refreshes only near expiry:

// proxy.ts (Next.js 16)
import { NextResponse, type NextRequest } from 'next/server'
import { ACCESS_COOKIE, REFRESH_COOKIE, accessCookie, refreshCookie, refreshTokens } from '@/lib/session'
import { expiresSoon } from '@/lib/jwt' // decodes `exp` only; the API still verifies the signature

export async function proxy(req: NextRequest) {
  const access = req.cookies.get(ACCESS_COOKIE)?.value
  const refresh = req.cookies.get(REFRESH_COOKIE)?.value
  if (!refresh || (access && !expiresSoon(access, 60))) return NextResponse.next()

  const result = await refreshTokens(refresh)
  if (result.status === 'unavailable') return NextResponse.next()
  if (result.status === 'rejected') {
    req.cookies.delete([ACCESS_COOKIE, REFRESH_COOKIE])
    const res = NextResponse.next({ request: { headers: req.headers } })
    res.cookies.delete(ACCESS_COOKIE)
    res.cookies.delete(REFRESH_COOKIE)
    return res
  }
  // 1. Downstream: Server Components in this same request see the new token
  req.cookies.set(ACCESS_COOKIE, result.accessToken)
  req.cookies.set(REFRESH_COOKIE, result.refreshToken)
  const res = NextResponse.next({ request: { headers: req.headers } })
  // 2. Browser: persist it for the next request
  res.cookies.set(ACCESS_COOKIE, result.accessToken, accessCookie)
  res.cookies.set(REFRESH_COOKIE, result.refreshToken, refreshCookie)
  return res
}

export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] }

With cookies set only on the response, the page rendering now still reads the old token from the incoming Cookie header and gets a 401. request.cookies.set rewrites that header on req.headers, and NextResponse.next({ request: { headers } }) passes it downstream. It has to be request: { headers }. Plain headers sends them back to the browser.

A rejected refresh only clears the cookies, with no redirect, so public pages still render. After the proxy, Server Components read the cookie through a server-only module and redirect to login on a 401. Server Actions can write cookies, so they refresh and retry once with a new request. My first version awaited the original, already-settled fetch promise, which always gives back the same 401. The refresh call goes through that wrapper too, so it needs a skipRefresh flag or it loops.

Ten 401s, one refresh

In the browser, a 401 triggers the refresh Route Handler for new cookies, then a retry:

// app/api/auth/refresh/route.ts
import { cookies } from 'next/headers'
import { ACCESS_COOKIE, REFRESH_COOKIE, accessCookie, refreshCookie, refreshTokens } from '@/lib/session'

export async function POST(req: Request) {
  const site = req.headers.get('sec-fetch-site')
  if (site && site !== 'same-origin') return new Response(null, { status: 403 })

  const store = await cookies()
  const refresh = store.get(REFRESH_COOKIE)?.value
  if (!refresh) return new Response(null, { status: 401 })

  const result = await refreshTokens(refresh)
  if (result.status === 'unavailable') return new Response(null, { status: 503 })
  if (result.status === 'rejected') {
    store.delete(ACCESS_COOKIE)
    store.delete(REFRESH_COOKIE)
    return new Response(null, { status: 401 })
  }
  store.set(ACCESS_COOKIE, result.accessToken, accessCookie)
  store.set(REFRESH_COOKIE, result.refreshToken, refreshCookie)
  return new Response(null, { status: 204 })
}

The client-side Axios interceptor (Axios 1.x), with the shared refreshing promise that turns those five 401s into one refresh:

// lib/http.ts
import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'

export const http = axios.create({ baseURL: '/api' })
let refreshing: Promise<unknown> | null = null

function refreshOnce() {
  // Plain axios, not `http`, so the refresh call never enters this interceptor
  refreshing ??= axios.post('/api/auth/refresh').finally(() => { refreshing = null })
  return refreshing
}

http.interceptors.response.use(undefined, async (error: AxiosError) => {
  const config = error.config as (InternalAxiosRequestConfig & { _retry?: boolean }) | undefined
  if (error.response?.status !== 401 || !config || config._retry) return Promise.reject(error)

  config._retry = true
  try {
    await refreshOnce()
  } catch (refreshError) {
    if (axios.isAxiosError(refreshError) && refreshError.response?.status === 401) {
      window.location.assign('/login')
    }
    return Promise.reject(refreshError)
  }
  return http(config) // the new cookie rides along automatically
})

The first version had no _retry flag, so a retry that got a 401 retried forever. The next two called redirect() from next/navigation inside the interceptor, but that function is for rendering, Server Actions and Route Handlers; on the client, use the router or window.location.

The bug that annoyed me most was a Promise.reject(error) with no return. The async interceptor resolved with undefined and the caller got undefined data instead of an error. Nothing threw, so it sat there for about ten months.

Rotation and CSRF on the backend

With rotation, every refresh issues a new token and invalidates the old one. The shared promise only dedupes within a tab, and a navigation plus a few prefetches can still send the same old token several times. The backend needs a short grace window before treating reuse as theft and revoking the whole family, plus a transaction so two rotations can't both pass. I've only sketched this and it doesn't run anywhere. The 10-second grace window in the sketch is a guess.

The refresh endpoint authenticates with the refresh token itself, not an expired access token, and the backend should keep only hashes. Logout should be a Server Action that revokes the session and clears the cookies even if the API call fails.

SameSite=Lax still sends cookies on top-level GET navigations, so never change data on a GET. Server Actions only accept POST, and Next.js compares Origin with Host (list a reverse proxy on another domain in serverActions.allowedOrigins). Route Handlers don't get that check, so handlers that change data check Origin or Sec-Fetch-Site themselves, like the refresh handler. Calling an API on another site directly needs SameSite=None plus a CSRF token, so I keep everything same-site.

Sockets and caching

A same-site Socket.IO server gets the cookie with withCredentials: true and credentials allowed in CORS; otherwise use a short-lived ticket from a Route Handler. On an auth-looking connect_error, refresh once through the shared promise and reconnect.

For session data I set cache: 'no-store' explicitly. force-cache doesn't put every user in one entry, because the fetch cache key includes request headers, but a per-token cache still needs an expiry policy. A 'use cache' function can't read cookies(), and a response that sets auth cookies shouldn't be cached by a shared CDN.

To test the flow, I expire a token in the middle of parallel requests and make the refresh endpoint reject a token. I also take the API down for a moment. Only the rejected refresh should end the session.

  • Next.js
  • Authentication
  • App Router
  • Security
  • JWT
  • Axios

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.