Dev.to Security 🔐 Cybersecurity 👁 0 📖 11 min read

Refresh Token Rotation in NestJS and Next.js: Reuse Detection, Token Families, and the Parallel-Refresh Race — Field Notes

Headline: Refresh token rotation means the server issues a new refresh token on every refresh and invalidates the old one; reuse detection means that when an already-rotated refresh token comes back, the server revokes e

Headline: Refresh token rotation means the server issues a new refresh token on every refresh and invalidates the old one; reuse detection means that when an already-rotated refresh token comes back, the server revokes every token from that login. In a NestJS API behind a Next.js App Router frontend, I store only SHA-256 hashes of opaque refresh tokens in Postgres, rotate them with one compare-and-set UPDATE, and allow a 10-second grace window so parallel refreshes from the same browser are not mistaken for theft.

The session design I started from is a common one: a short-lived JWT access token and a 30-day refresh token, both in httpOnly cookies, and a refresh endpoint that signs a new access token and leaves the refresh token untouched. It works until the refresh token leaks. Whoever holds a copy has a 30-day session, and the server cannot tell the two holders apart. These are my notes on replacing that design with rotation and reuse detection, and on the concurrency bug that shows up as soon as you do.

Key takeaways

  • Refresh token rotation replaces the refresh token on every use, so a leaked refresh token stays valid only until someone uses it.
  • Reuse detection treats a second use of an already-rotated refresh token as theft and revokes the whole token family — every refresh token descended from one login.
  • Refresh tokens should be opaque random strings stored as SHA-256 hashes, not JWTs, because the server has to look each one up to rotate and revoke it anyway.
  • Rotation must be an atomic compare-and-set (UPDATE … WHERE rotated_at IS NULL … RETURNING), or two concurrent requests can both consume the same refresh token.
  • Parallel refreshes from one browser look exactly like token theft, so the client needs a single-flight refresh and the server needs a short grace window.

What do refresh token rotation and reuse detection protect against?

Refresh token rotation and reuse detection limit how long a stolen refresh token stays useful and make its use detectable. A refresh token is a long-lived credential whose only job is to obtain new short-lived access tokens; the access token is the credential the API checks on every request.

Without rotation, one refresh token works for its whole lifetime, so a copy leaked through a log line, a compromised device or a misconfigured proxy is a silent second session. With rotation, every successful refresh returns a new refresh token and marks the old one as used. If the attacker refreshes first, the legitimate client's next refresh presents a used token; if the client refreshes first, the attacker's attempt does. In both cases the server sees a rotated token come back, cannot tell which caller is legitimate, and revokes the family. Both sessions end, and the real user signs in again.

RFC 9700, the OAuth 2.0 Security Best Current Practice published in January 2025, requires refresh tokens issued to public clients to be either sender-constrained or rotated. A first-party Next.js and NestJS session is not an OAuth flow, but a refresh cookie faces the same threat model.

How should I store refresh tokens in Postgres?

I store each refresh token as a row keyed by the SHA-256 hash of an opaque random string, grouped by a family_id created at login. The raw token exists only in the cookie, so a database leak exposes hashes that cannot be replayed.

CREATE TABLE refresh_tokens (
  id                uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  family_id         uuid NOT NULL,          -- one per login
  user_id           uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
  token_hash        bytea NOT NULL UNIQUE,  -- sha256(raw token)
  expires_at        timestamptz NOT NULL,   -- idle timeout of this token
  family_expires_at timestamptz NOT NULL,   -- absolute session lifetime
  rotated_at        timestamptz,            -- set when this token is used
  revoked_at        timestamptz,            -- set on reuse or logout
  created_at        timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX refresh_tokens_family_idx ON refresh_tokens (family_id);

Each raw token is 32 bytes from crypto.randomBytes(), encoded as base64url. A fast hash such as SHA-256 is enough because the input already has 256 bits of entropy; slow password hashes like bcrypt exist for low-entropy passwords and would also rule out a unique-index lookup. The two expiry columns do different jobs: expires_at is the idle timeout of one token, and family_expires_at is the absolute session lifetime. I clamp every new token's expires_at to family_expires_at, so rotation keeps an active session alive without ever extending it past the absolute limit. The values I use are 10 minutes for access tokens, 7 days idle and 30 days absolute.

How do I rotate a refresh token atomically in NestJS?

Atomic rotation is a single UPDATE that moves rotated_at off NULL and returns the row, so exactly one request can consume a given refresh token. A read-then-write version — SELECT the row, check it in TypeScript, then UPDATE it — lets two concurrent requests both pass the check and both receive successors.

// auth/refresh-token.service.ts
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { createHash, randomBytes } from 'node:crypto';
import { Pool } from 'pg';

const IDLE_MS = 7 * 24 * 60 * 60 * 1000;
const sha256 = (raw: string) => createHash('sha256').update(raw).digest();

type Family = { family_id: string; user_id: string; family_expires_at: Date };

@Injectable()
export class RefreshTokenService {
  constructor(
    @Inject('PG_POOL') private readonly pool: Pool,
    private readonly jwt: JwtService,
  ) {}

  async rotate(raw: string) {
    const hash = sha256(raw);

    // Compare-and-set: only one request can move rotated_at off NULL
    const consumed = await this.pool.query<Family>(
      `UPDATE refresh_tokens SET rotated_at = now()
        WHERE token_hash = $1 AND rotated_at IS NULL AND revoked_at IS NULL
          AND expires_at > now()
        RETURNING family_id, user_id, family_expires_at`,
      [hash],
    );
    if (consumed.rows[0]) return this.issue(consumed.rows[0]);

    const { rows: [seen] } = await this.pool.query<Family & { rotated: boolean; in_grace: boolean }>(
      `SELECT family_id, user_id, family_expires_at,
              rotated_at IS NOT NULL AS rotated,
              rotated_at > now() - interval '10 seconds'
                AND revoked_at IS NULL AND expires_at > now() AS in_grace
         FROM refresh_tokens WHERE token_hash = $1`,
      [hash],
    );
    if (seen?.in_grace) return this.issue(seen); // parallel refresh from the same browser
    if (seen?.rotated) {
      // A used token came back after the grace window: assume it was stolen
      await this.pool.query(
        `UPDATE refresh_tokens SET revoked_at = now()
          WHERE family_id = $1 AND revoked_at IS NULL`,
        [seen.family_id],
      );
    }
    throw new UnauthorizedException();
  }

  private async issue(f: Family) {
    const refreshToken = randomBytes(32).toString('base64url');
    const expiresAt = new Date(Math.min(Date.now() + IDLE_MS, f.family_expires_at.getTime()));
    await this.pool.query(
      `INSERT INTO refresh_tokens (family_id, user_id, token_hash, expires_at, family_expires_at)
       VALUES ($1, $2, $3, $4, $5)`,
      [f.family_id, f.user_id, sha256(refreshToken), expiresAt, f.family_expires_at],
    );
    const accessToken = await this.jwt.signAsync(
      { sub: f.user_id, sid: f.family_id },
      { expiresIn: '10m' },
    );
    return { accessToken, refreshToken, expiresAt };
  }
}

Every call to rotate() ends in one of four outcomes: a normal rotation, a grace-window refresh, a reuse that revokes the family, or a plain 401 for unknown and expired tokens. Expired tokens never trigger revocation, because an old cookie on a laptop that slept for a month is not an attack. In production I run the consuming UPDATE and the successor INSERT in one transaction, so a crash between them cannot leave a session without a valid token.

The controller reads the cookie through cookie-parser and writes both cookies with @Res({ passthrough: true }), which keeps NestJS's normal response handling:

// auth/auth.controller.ts (global prefix: /api)
@Post('refresh')
@HttpCode(200)
async refresh(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
  const raw = req.cookies?.['__Secure-rt'];
  if (!raw) throw new UnauthorizedException();

  const { accessToken, refreshToken, expiresAt } = await this.tokens.rotate(raw);
  // Proxy-driven design; the browser-driven variant scopes __Secure-rt to /api/auth/refresh
  const base = { httpOnly: true, secure: true, sameSite: 'lax', path: '/' } as const;
  res.cookie('__Secure-at', accessToken, { ...base, maxAge: 10 * 60 * 1000 });
  res.cookie('__Secure-rt', refreshToken, { ...base, expires: expiresAt });
  return { ok: true };
}

The __Secure- cookie name prefix makes browsers reject the cookie unless it is set with the Secure attribute from an HTTPS origin; the stricter __Host- prefix requires Path=/, so it cannot be combined with a path-scoped refresh cookie. Reuse detection also has one known gap: an access token already issued to an attacker stays valid until its exp claim. Short access tokens bound that gap, and sensitive endpoints can check the sid claim against revoked families.

Why does refresh token rotation log users out at random?

Refresh token rotation logs users out when two requests from the same browser refresh with the same token at the same time: the first request rotates it, and the second presents a token that is already rotated, which is exactly what theft looks like. Every tab shares one cookie jar, so the race happens whenever two tabs wake up together, a page fires parallel API calls after the access token expires, or the Next.js router prefetches several routes at once.

I fix it on both sides. In the browser, every 401 goes through one single-flight refresh, and the Web Locks API — navigator.locks.request(), available in current Chrome, Edge, Firefox and Safari — serializes refreshes across tabs of the same origin:

// lib/api-fetch.ts (browser only)
let inflight: Promise<boolean> | null = null;

export function refreshSession(): Promise<boolean> {
  // One refresh per tab (single-flight), one tab at a time (Web Locks)
  inflight ??= navigator.locks
    .request('auth-refresh', async () => {
      const res = await fetch('/api/auth/refresh', { method: 'POST' });
      return res.ok;
    })
    .finally(() => {
      inflight = null;
    });
  return inflight;
}

export async function apiFetch(input: string, init?: RequestInit) {
  const res = await fetch(input, init);
  if (res.status !== 401 || !(await refreshSession())) return res;
  return fetch(input, init); // retry once with the new access cookie
}

When the second tab acquires the lock, the cookie jar already holds the new refresh token, so its refresh is an ordinary rotation rather than a reuse. On the server, the grace window in rotate() accepts a just-rotated token for 10 seconds and issues another successor in the same family instead of revoking it. The grace window is also a short theft window, so I keep it to seconds. Hosted identity providers such as Auth0 and Okta expose the same trade-off as a configurable leeway or grace period on refresh token rotation.

Should a Next.js App Router app refresh in the proxy or in the browser?

Next.js Server Components cannot set cookies, so a Server Component that finds an expired access token cannot rotate the session itself. Only Route Handlers, Server Actions and the proxy — the file named middleware.ts before Next.js 16 — can write cookies, which leaves two workable designs:

Browser-driven refresh Proxy-driven refresh
Refresh cookie scope Path=/api/auth/refresh, SameSite=Strict Path=/, SameSite=Lax
Who notices expiry The fetch wrapper, after a 401 The proxy, before each page render
Server Components with an expired access token Render a signed-out state; the client refreshes and calls router.refresh() Always receive a fresh access token
Concurrent refresh protection Single-flight plus Web Locks Server grace window
Where the refresh cookie travels One endpoint Every page request

I use proxy-driven refresh when most data loads in Server Components, because every render then sees a valid access token. The proxy rotates the session before rendering, copies the new cookies into the current request with request.cookies.set(), and passes the Set-Cookie headers from NestJS to the browser unchanged:

// proxy.ts (named middleware.ts before Next.js 16)
import { NextResponse, type NextRequest } from 'next/server';
import { decodeJwt } from 'jose';

function accessExpiry(token?: string) {
  try {
    return token ? (decodeJwt(token).exp ?? 0) : 0;
  } catch {
    return 0; // malformed cookie: treat as expired
  }
}

export async function proxy(request: NextRequest) {
  const refresh = request.cookies.get('__Secure-rt')?.value;
  const exp = accessExpiry(request.cookies.get('__Secure-at')?.value);
  // Refresh only when the access token is missing or expires within 60 s
  if (!refresh || exp - 60 > Date.now() / 1000) return NextResponse.next();

  const upstream = await fetch(`${process.env.API_URL}/api/auth/refresh`, {
    method: 'POST',
    headers: { cookie: `__Secure-rt=${refresh}` },
  });
  if (!upstream.ok) return NextResponse.next(); // the page decides whether to redirect

  const setCookies = upstream.headers.getSetCookie();
  for (const line of setCookies) {
    const pair = line.split(';')[0];
    const eq = pair.indexOf('=');
    request.cookies.set(pair.slice(0, eq), pair.slice(eq + 1)); // visible to this render
  }
  const response = NextResponse.next({ request });
  for (const line of setCookies) response.headers.append('set-cookie', line); // stored by the browser
  return response;
}

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

decodeJwt() from jose only reads the exp claim to decide when to refresh; NestJS still verifies the signature on every API call. Parallel React Server Component (RSC) prefetches can run the proxy concurrently with the same refresh cookie, which is the case the server grace window exists for. For dashboards that fetch mostly from the browser, I use the browser-driven variant with the refresh cookie scoped to Path=/api/auth/refresh, so the long-lived credential is never sent anywhere else.

FAQ

Q: Should refresh tokens be JWTs?

A: No. A refresh token should be an opaque random string stored as a hash, because the server must look it up on every use to rotate and revoke it. A JWT refresh token adds size and a signing key without removing that lookup.

Q: Is refresh token rotation enough, or do I need DPoP?

A: Rotation detects a stolen refresh token after it is used; DPoP (Demonstrating Proof of Possession, RFC 9449) binds tokens to a key pair held by the client, so a copied token cannot be used at all. For a first-party browser app with httpOnly cookies, rotation plus short-lived access tokens is a reasonable baseline, and sender-constrained tokens are the next step for high-risk apps.

Q: What should logout do with refresh tokens?

A: Logout should revoke the entire token family and clear both cookies. Revoking only the current row leaves any sibling token issued during a grace-window refresh valid until it expires.

Q: How long should the reuse grace window be?

A: The grace window should cover a burst of parallel requests from one page load and nothing more. I use 10 seconds; check the gap between duplicate refreshes in your own logs before making it longer.

Q: Why not keep the refresh token in localStorage?

A: Any script on the page can read localStorage, so one XSS bug can exfiltrate a refresh token and replay it from another machine. An httpOnly cookie is unreadable from JavaScript, so an XSS bug can still act inside the open tab but cannot steal the long-lived credential.

Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.