Skip to content

Guide · November 26, 2026 · 4 min read

NextAuth + Django JWT: refresh tokens without session leaks

How to store Django REST Framework JWTs in NextAuth, refresh them safely from server and client, avoid handing one user another user's tokens, and sign out cleanly.


Pairing NextAuth (Auth.js) with a Django REST Framework API that issues JWTs — SimpleJWT, typically — is a common setup, and most of it is straightforward. The refresh path is not. These are the decisions that matter, including one bug that silently signs users in as each other.

Where each token lives

  • Refresh token: inside the NextAuth JWT, which is stored encrypted in an HTTP-only cookie. It is only ever read server-side, in the jwt callback.
  • Access token: copied into the session so the browser can attach it to API calls. It is short-lived: SimpleJWT’s default is five minutes; SaaS Dock uses an hour.

The split is the security boundary. If you add the refresh token to the Session type “for convenience”, it reaches client JavaScript, and any XSS can mint new access tokens for as long as it likes. Type the two shapes separately so the compiler stops you:

declare module 'next-auth' {
  interface Session { accessToken?: string; error?: RefreshError }
}
declare module 'next-auth/jwt' {
  interface JWT { accessToken?: string; refreshToken?: string; error?: RefreshError }
}

Refresh in the jwt callback, only when needed

async jwt({ token }) {
  if (isTokenExpired(token.accessToken)) {
    const refresh = token.refreshToken
    if (refresh && !isTokenExpired(refresh)) {
      try {
        const data = await getRefreshedToken(refresh)
        token.accessToken = data.access
        token.refreshToken = data.refresh
        delete token.error
      } catch (error) {
        token.error = refreshErrorFor(error)
      }
    } else {
      token.error = 'RefreshTokenExpired'
    }
  }
  return token
}

The bug: a module-level refresh lock

The jwt callback runs concurrently — several tabs, server components and client requests can all find the access token expired at once. The tempting fix is to share one in-flight promise:

// DO NOT do this
let refreshing: Promise<Tokens> | null = null

But that callback runs on the server, in a process shared by every visitor. When user A’s and user B’s refreshes overlap, B awaits A’s promise and receives A’s tokens. B is now signed in as A. Nothing errors.

Key the lock by the refresh token, and delete the entry when it settles:

const refreshPromises = new Map<string, Promise<Tokens>>()

function getRefreshedToken(refreshToken: string) {
  const inFlight = refreshPromises.get(refreshToken)
  if (inFlight) return inFlight
  const promise = fetchRefresh(refreshToken).finally(() => refreshPromises.delete(refreshToken))
  refreshPromises.set(refreshToken, promise)
  return promise
}

Pin it with a test that runs two users’ refreshes concurrently and asserts each gets their own tokens.

Rotation and server components

With ROTATE_REFRESH_TOKENS, every refresh returns a new refresh token. A React Server Component can trigger a refresh but cannot write the cookie back, so the browser still holds the old refresh token. If you also enable BLACKLIST_AFTER_ROTATION, that old token is now dead and the session breaks after the first server-side refresh. Either keep the previous token valid until it expires, or make sure only code that can write the cookie refreshes.

Tell a dead session from a network blip

A failed refresh means one of two very different things:

  • The API refused the token (401). It was revoked, its session was closed from another device, or the account was deleted. Retrying can never succeed — sign the user out.
  • The request failed (timeout, 5xx, network). The token is still good. Fail this request and let the next one try again; signing out here logs every open tab out on a ten-second outage.
const refreshErrorFor = (error: unknown) =>
  error instanceof RefreshRejectedError ? 'RefreshTokenExpired' : 'RefreshTokenError'

Your HTTP client then signs out on RefreshTokenExpired and only fails the request on RefreshTokenError.

Revoke on the server, too

Sign-out should blacklist the refresh token on the API, not just clear the cookie. And because access tokens are stateless, a blacklist alone leaves the current access token valid for the rest of its lifetime. Carrying a session id claim in every token lets the API refuse all tokens of a closed session — which is also what powers an “active sessions” screen. We cover that in 2FA recovery codes and session management in Django.

Sign-in must not depend on the session it replaces

Route login, 2FA, password reset and Google sign-in through a plain HTTP client with no auth interceptors. If the authenticated client refuses to send while the current session is broken, a stale cookie makes it impossible to log back in.

Checklist

  • Refresh token only on the server-side JWT; access token in the session
  • Refresh only when the access token is near expiry
  • In-flight refreshes keyed by refresh token, never module-wide
  • Rotation compatible with server components that cannot write cookies
  • 401 on refresh signs out; network errors do not
  • Server-side revocation that also stops access tokens
  • Auth flows on a client without interceptors

SaaS Dock’s Next.js app implements this flow against its Django API, with regression tests for the per-token lock and the dead-session handling. See what’s inside.

Frequently asked questions

Where should the Django refresh token live in a Next.js app?
Inside the encrypted NextAuth JWT cookie, on the server-side token only. Expose the short-lived access token to the browser through the session, but never the refresh token.
Why do concurrent token refreshes break NextAuth sessions?
The jwt callback can run several times at once for the same user (several tabs, server components, client requests). Deduplicating those refreshes with a single module-level promise is a serious bug, because the callback runs in a server process shared by every visitor: one user can receive another user's tokens. Key the in-flight refresh by the refresh token instead.