BoilerShelf

Part 9 · Building AI products

FastAPI and Next.js JWT Auth With Refresh Token Rotation

Implement refresh token rotation in FastAPI and Next.js with an atomic database exchange, HttpOnly cookies, and explicit CSRF checks.

B

BoilerShelf Team

November 16, 2026 · 5 min read

A pale teal token lying beside an upright dark teal token in an ivory tray.

Short answer: For FastAPI and Next.js JWT authentication, issue a short-lived access JWT that the browser keeps in memory, and an opaque refresh token in an HttpOnly cookie that the server rotates on every use. Store only a digest of the refresh token, and revoke the whole session family if a used token appears again.

How should you issue the access JWT and the refresh token cookie?

Issue a short-lived, signed access JWT and keep it in browser memory when using this client-side architecture. Verify the signature with a fixed algorithm allowlist and validate the expected issuer, audience, expiry and subject. Enforce access-token purpose separately when several token types share a verification service. Treat embedded roles as snapshots. A role change or logout requires a state check for immediate invalidation, otherwise already-issued JWTs remain usable until expiry.

Create an opaque refresh token with a cryptographically secure random generator and store its digest with a server-side session family. Set a host-only cookie by omitting Domain. Use HttpOnly, Secure and an explicit SameSite policy. Set Path to the actual public auth route prefix, including any browser-facing proxy prefix. Match that Path and Domain scope when clearing it. Set its lifetime to the persisted token expiry, and send auth responses with Cache-Control: no-store.

Sources: JWT Best Current Practices · PyJWT validation API · Set-Cookie reference

How do you rotate a refresh token safely in one transaction?

In this PostgreSQL example, login creates the family and first token in one transaction. The app hashes the presented token and generates the next high-entropy value, then submits only the digests. Run rotation at READ COMMITTED. Lock the family, re-read the token after acquiring the lock, mark its use, and insert one successor. Apply the same family lock discipline to revocation and cleanup. Keep consumed digests for the family’s active lifetime so the server can recognize a previously used token.

-- Populate one family and its first token at login.
CREATE TABLE refresh_family (
    id uuid PRIMARY KEY,
    user_id uuid NOT NULL,
    expires_at timestamptz NOT NULL,
    revoked_at timestamptz
);
CREATE TABLE refresh_token (
    digest bytea PRIMARY KEY,
    family_id uuid NOT NULL REFERENCES refresh_family(id),
    expires_at timestamptz NOT NULL,
    used_at timestamptz
);
CREATE UNIQUE INDEX one_unused_refresh_per_family
    ON refresh_token (family_id) WHERE used_at IS NULL;

CREATE FUNCTION rotate_refresh(
    old_digest bytea, next_digest bytea
) RETURNS text LANGUAGE plpgsql AS $$
DECLARE
    family refresh_family%ROWTYPE;
    token refresh_token%ROWTYPE;
    now_at timestamptz;
BEGIN
    -- All operations that change a family take this lock first.
    SELECT f.* INTO family
      FROM refresh_family AS f
      JOIN refresh_token AS t ON t.family_id = f.id
     WHERE t.digest = old_digest
       FOR UPDATE OF f;
    IF NOT FOUND THEN RETURN 'invalid'; END IF;

    now_at := clock_timestamp();
    IF family.revoked_at IS NOT NULL OR family.expires_at <= now_at THEN
        RETURN 'invalid';
    END IF;

    SELECT * INTO token FROM refresh_token WHERE digest = old_digest;
    IF NOT FOUND THEN RETURN 'invalid'; END IF;
    IF token.used_at IS NOT NULL THEN
        UPDATE refresh_family SET revoked_at = now_at WHERE id = family.id;
        RETURN 'revoked';
    END IF;
    IF token.expires_at <= now_at THEN RETURN 'invalid'; END IF;

    UPDATE refresh_token SET used_at = now_at WHERE digest = old_digest;
    INSERT INTO refresh_token (digest, family_id, expires_at)
    VALUES (
        next_digest, family.id,
        LEAST(family.expires_at, now_at + interval '14 days')
    );
    RETURN 'rotated';
END;
$$;

The app must commit the transaction before emitting a new cookie or returning 401. In particular, commit the revoked outcome before converting it to an HTTP error, so exception handling cannot undo revocation. On rotation, read the user and successor expiry in the same transaction and prepare the access token before returning the response. Map invalid and revoked to the same public response, clear the cookie, and keep reasons in internal telemetry without logging token values. Commit logout and password-change revocations under the same lock discipline.

The SQL example passed tests on PostgreSQL 18.6 (PGlite) for rotation, unknown or expired tokens, pre-consumed tokens, family revocation and rollback when the successor insert fails. It demonstrates one PostgreSQL persistence design. Verify concurrent refresh and logout using independent database sessions before release. MongoDB requires its own transaction design and tests.

Sources: PostgreSQL row locks · OAuth refresh token guidance

How should Next.js coordinate refreshes across requests and tabs?

Keep one in-flight refresh promise per browser tab. To reduce simultaneous refreshes across tabs, coordinate through a same-origin lock where supported, and recheck auth state after taking the lock. Keep this token state client-side and scoped to the current app session. A lost response after rotation can require signing in again. On an authenticated API request, retry at most once after an explicit access-token-expired response. Restrict automatic retries to safe operations or requests that have an established idempotency contract.

Clear in-memory auth state on logout or an invalid refresh. Show a retryable error on temporary network failure. In Next.js, scope server-side credentials per request. If a Route Handler sets the browser cookie, configure its actual public path and forward Set-Cookie deliberately. A same-origin proxy can simplify browser cookie and CORS behavior.

Sources: Next.js cookies · Web Locks API

Do you need CSRF protection and a CORS policy?

Protect login, refresh and logout, because these endpoints set, rotate or clear cookies and affect session state. Verify the exact trusted Origin on state-changing requests, with a documented policy for missing or null origins. Use a framework-supported CSRF token where appropriate, for example a signed token bound to the session and submitted in a custom header. A strict SameSite policy is an additional layer. CORS controls whether browser scripts can read cross-origin responses and which preflighted calls are allowed. Treat CSRF validation as its own server-side check.

If the app and API have different origins, send credentials: include only to the trusted API on cookie-backed auth calls. Configure exact allowed origins, methods and headers. Subdomains can be cross-origin and still same-site when their schemes and registrable domain match. If deployment requires a cross-site cookie, SameSite=None also requires Secure, and browser third-party cookie rules can still block it. Prefer a same-site or same-origin design when you control the deployment.

Sources: OWASP CSRF Prevention Cheat Sheet · FastAPI CORS guide

Frequently asked questions

Is localStorage safe for a JWT?

Any script that runs on your page can read it, so a cross-site scripting flaw exposes the token. Keeping the access token in memory and the refresh token in an HttpOnly cookie reduces what a script can steal. It does not remove the need to prevent XSS, because a malicious script can still make requests from the page.

How long should an access token live?

Minutes. Fifteen is a common choice. The shorter it is, the less a stolen one is worth, and the refresh flow hides the expiry from users.

Why store the refresh token as a hash?

So that a leaked database table does not contain usable tokens. A fast hash such as SHA-256 is enough for a long random value.

Where to go next

For a ready implementation, see the Auth Boilerplate, a FastAPI and Next.js source-code kit with MongoDB and PostgreSQL editions.

The idea in short

Login returns a short-lived access token in the response body and sets a refresh token in an HttpOnly cookie. When the access token expires, the frontend calls the refresh route, the server swaps the refresh token for a new one and marks the old one used. If a used token appears again, the server revokes the whole token family.

Patterns covered: Access and refresh tokens · Refresh token rotation · Reuse detection · HttpOnly cookies

  • FastAPI
  • Jwt
  • Authentication
  • Next.js
  • Security

New guides and boilerplates, by email

Leave your email and we will tell you when a new guide or boilerplate is published.

All guides
FastAPI JWT Auth With Rotating Refresh Tokens | BoilerShelf