The Practical Developer

JWT Refresh Token Rotation: Stop Stolen Sessions from Lasting Forever

You cannot revoke a JWT without a database round-trip, so stop pretending it is stateless. Build a secure session model with short-lived access tokens, httpOnly refresh cookies, rotation, and reuse detection in Node.js.

Close-up of a metallic padlock on a circuit board, representing the tension between token convenience and session security

The user logs in. You sign a JWT, set a 24-hour expiry, and send it back. The frontend stores it in localStorage and attaches it to every request. Three months later, a stored XSS payload fires on a comment page, exfiltrates every token in localStorage, and the attacker now has session access until every single token expires. You rotate the signing key. The old tokens are still valid until their exp claim ticks over. You have no server-side list of active sessions. All you can do is wait.

This is the reality of stateless JWT sessions done the way most tutorials teach them. Stateless is not a feature when you need to revoke access. And long-lived tokens stored in localStorage are a sitting target for any XSS, malicious browser extension, or CDN compromise that injects a script tag.

The fix is not “switch to session cookies and abandon JWTs.” The fix is to stop using JWTs as session tokens. Use short-lived JWT access tokens as authorization credentials and long-lived opaque refresh tokens stored in httpOnly cookies as session anchors. Rotate the refresh token on every use. Detect reuse. Store the token family in a database so you can revoke a compromised session in a single DELETE. This post builds the complete Node.js implementation: login, refresh, logout, and the reuse detection that catches token theft.

Why localStorage JWTs fail in production

Most JWT tutorials ship this flow:

  1. User POSTs /login.
  2. Server signs a JWT with exp: 24h.
  3. Frontend stores it in localStorage.
  4. Frontend sends Authorization: Bearer <token> on every request.

The problems are immediate and compound over time.

XSS is the obvious one. Any script running on your origin can read localStorage and exfiltrate the token. Content Security Policy helps, but CSP is a defense in depth, not a guarantee. A single missed script-src directive, a compromised npm package injecting inline scripts, or a JSONP endpoint you forgot about all bypass it.

The subtler problem is revocation. A JWT is valid until it expires. If a user reports their account compromised, or you detect a breach, or an employee leaves and needs instant access termination, you cannot revoke a token without maintaining a blocklist. A blocklist checked on every request is a database round-trip, which removes the supposed performance benefit of stateless tokens.

Long-lived access tokens make both problems worse. A 24-hour window is an eternity for an attacker. A 5-minute window is short enough to limit damage, but only if the refresh mechanism is secure.

The architecture: access tokens versus refresh tokens

Split the problem into two tokens with different jobs.

An access token is a short-lived JWT, 5 to 15 minutes, containing the user’s identity, roles, and any claims the API needs to authorize requests. It travels in the Authorization header. It is stateless. The API can verify it with just the public key or shared secret.

A refresh token is a long-lived opaque value, a cryptographically random string, stored server-side and delivered to the client in an httpOnly, Secure, SameSite=Strict cookie. It is not a JWT. It does not contain claims. It is just a lookup key into a database table that stores the user ID, token family, expiration, and creation metadata.

The frontend never sees the refresh token as a string. The browser sends it automatically as a cookie when it calls /refresh. The server validates it, issues a new access token, rotates the refresh token (issues a new one and invalidates the old), and sends both back.

If an attacker steals the access token, they have 5 minutes of access. If they steal the refresh token from the cookie, they need to use it before the legitimate client does, because the first use rotates it. If both the attacker and the victim present the same refresh token, you know theft occurred and you revoke the entire token family.

The database schema

You need a table for refresh tokens. Keep it simple.

CREATE TABLE refresh_tokens (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  token_hash text NOT NULL UNIQUE,
  token_family uuid NOT NULL,
  expires_at timestamptz NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  revoked_at timestamptz,
  replaced_by uuid REFERENCES refresh_tokens(id)
);

CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id);
CREATE INDEX idx_refresh_tokens_token_hash ON refresh_tokens(token_hash);

The token_hash stores SHA-256(refreshToken) so that even a database dump does not expose valid tokens. The token_family groups tokens from the same login session. When a user logs in, they get a new token_family. Every rotation within that session keeps the same family but chains replaced_by.

revoked_at is the kill switch. When set, any presentation of that token or any later token in the same family is rejected.

Generating tokens

Use crypto.randomBytes for refresh tokens. Do not use JWTs for refresh tokens. JWTs are designed for stateless verification. Refresh tokens are intentionally stateful: their only purpose is to be looked up in a database.

import crypto from 'node:crypto';

function generateRefreshToken(): string {
  return crypto.randomBytes(32).toString('base64url');
}

function hashToken(token: string): string {
  return crypto.createHash('sha256').update(token).digest('hex');
}

Access tokens are standard JWTs, short-lived, signed with your existing strategy.

import jwt from 'jsonwebtoken';

function createAccessToken(userId: string, roles: string[]): string {
  return jwt.sign(
    { sub: userId, roles },
    process.env.ACCESS_TOKEN_SECRET!,
    { expiresIn: '5m', algorithm: 'HS256' },
  );
}

For production, use RS256 with a key pair so the API gateway can verify tokens without holding the signing secret. HS256 is acceptable for a single service. Do not use none.

Login endpoint

app.post('/auth/login', async (req, res) => {
  const { email, password } = req.body;

  const user = await authenticateUser(email, password);
  if (!user) {
    return res.status(401).json({ error: 'invalid credentials' });
  }

  const accessToken = createAccessToken(user.id, user.roles);
  const refreshToken = generateRefreshToken();
  const tokenHash = hashToken(refreshToken);
  const family = crypto.randomUUID();

  await db.query(
    `INSERT INTO refresh_tokens (user_id, token_hash, token_family, expires_at)
     VALUES ($1, $2, $3, now() + interval '7 days')`,
    [user.id, tokenHash, family],
  );

  res.cookie('refresh_token', refreshToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 7 * 24 * 60 * 60 * 1000,
    path: '/auth/refresh',
  });

  res.json({ access_token: accessToken, token_type: 'Bearer', expires_in: 300 });
});

Notice the cookie path is /auth/refresh. The refresh token is only sent to the refresh endpoint. It never touches your business API routes, so a CSRF or XSS attack against /api/orders cannot steal it via a crafted request.

Also notice that we do not store the raw token in the database. Only the hash. If the database leaks, the attacker still needs to brute-force a 256-bit value, which is computationally infeasible.

The refresh endpoint: rotation and reuse detection

This is where the security lives. When a client sends the refresh cookie, the server must:

  1. Hash the presented token and look it up.
  2. If the token is revoked, expired, or already replaced, reject it.
  3. If the token is valid, create a new refresh token, mark the old one as replaced, and issue a new access token.
  4. If the same old token is presented twice (attacker and victim racing), detect reuse and revoke the entire family.
app.post('/auth/refresh', async (req, res) => {
  const rawToken = req.cookies.refresh_token;
  if (!rawToken) {
    return res.status(401).json({ error: 'missing refresh token' });
  }

  const tokenHash = hashToken(rawToken);

  const result = await db.query(
    `SELECT id, user_id, token_family, expires_at, revoked_at, replaced_by
     FROM refresh_tokens
     WHERE token_hash = $1`,
    [tokenHash],
  );

  if (result.rows.length === 0) {
    return res.status(401).json({ error: 'invalid refresh token' });
  }

  const token = result.rows[0];

  if (token.revoked_at || token.expires_at < new Date()) {
    return res.status(401).json({ error: 'refresh token revoked or expired' });
  }

  // Reuse detection: if this token was already replaced, someone is using a stolen copy.
  if (token.replaced_by) {
    await revokeTokenFamily(token.token_family);
    res.clearCookie('refresh_token', { path: '/auth/refresh' });
    return res.status(401).json({ error: 'token reuse detected, session terminated' });
  }

  // Issue new tokens
  const accessToken = createAccessToken(token.user_id, []);
  const newRefreshToken = generateRefreshToken();
  const newTokenHash = hashToken(newRefreshToken);
  const newFamily = token.token_family; // same family

  await db.query('BEGIN');

  try {
    const newTokenResult = await db.query(
      `INSERT INTO refresh_tokens (user_id, token_hash, token_family, expires_at)
       VALUES ($1, $2, $3, now() + interval '7 days')
       RETURNING id`,
      [token.user_id, newTokenHash, newFamily],
    );

    await db.query(
      `UPDATE refresh_tokens
       SET replaced_by = $1
       WHERE id = $2`,
      [newTokenResult.rows[0].id, token.id],
    );

    await db.query('COMMIT');
  } catch (error) {
    await db.query('ROLLBACK');
    throw error;
  }

  res.cookie('refresh_token', newRefreshToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 7 * 24 * 60 * 60 * 1000,
    path: '/auth/refresh',
  });

  res.json({ access_token: accessToken, token_type: 'Bearer', expires_in: 300 });
});

The revokeTokenFamily function sets revoked_at on every token in the family. This kills the attacker’s session immediately, even if they hold a newer rotated token.

async function revokeTokenFamily(family: string): Promise<void> {
  await db.query(
    `UPDATE refresh_tokens
     SET revoked_at = now()
     WHERE token_family = $1 AND revoked_at IS NULL`,
    [family],
  );
}

Logout and explicit revocation

Users expect a logout button to end their session everywhere, or at least on the current device. Support both.

app.post('/auth/logout', authenticateAccessToken, async (req, res) => {
  const rawToken = req.cookies.refresh_token;

  if (rawToken) {
    const tokenHash = hashToken(rawToken);
    await db.query(
      `UPDATE refresh_tokens
       SET revoked_at = now()
       WHERE token_hash = $1`,
      [tokenHash],
    );
    res.clearCookie('refresh_token', { path: '/auth/refresh' });
  }

  res.sendStatus(204);
});

app.post('/auth/logout-all', authenticateAccessToken, async (req, res) => {
  const userId = req.user!.sub;

  await db.query(
    `UPDATE refresh_tokens
     SET revoked_at = now()
     WHERE user_id = $1 AND revoked_at IS NULL`,
    [userId],
  );

  res.clearCookie('refresh_token', { path: '/auth/refresh' });
  res.sendStatus(204);
});

/logout revokes the current refresh token. /logout-all revokes every active token for the user. Because access tokens are short-lived, they will expire naturally within minutes. If you need immediate revocation of access tokens too, keep a list of revoked jti claims and check them in the authenticateAccessToken middleware. For 5-minute tokens, most systems accept the small window rather than adding a Redis round-trip to every API call.

Frontend changes

The frontend needs one small piece of logic: a request interceptor that catches 401 responses from API routes, calls /auth/refresh, retries the original request with the new access token, and only redirects to login if refresh fails.

let refreshPromise: Promise<string> | null = null;

async function fetchWithAuth(url: string, options: RequestInit = {}): Promise<Response> {
  const accessToken = localStorage.getItem('access_token');

  const response = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ${accessToken}`,
    },
  });

  if (response.status !== 401) return response;

  // Avoid multiple simultaneous refresh requests
  if (!refreshPromise) {
    refreshPromise = refreshAccessToken().finally(() => {
      refreshPromise = null;
    });
  }

  try {
    const newToken = await refreshPromise;
    return fetch(url, {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${newToken}`,
      },
    });
  } catch {
    localStorage.removeItem('access_token');
    window.location.href = '/login';
    throw new Error('session expired');
  }
}

async function refreshAccessToken(): Promise<string> {
  const response = await fetch('/auth/refresh', { method: 'POST', credentials: 'include' });
  if (!response.ok) throw new Error('refresh failed');

  const data = await response.json();
  localStorage.setItem('access_token', data.access_token);
  return data.access_token;
}

Note that credentials: 'include' is required so the browser sends the httpOnly cookie. The refresh token never touches JavaScript.

The threat model, addressed

XSS stealing the access token: The attacker gets 5 minutes. They cannot refresh without the cookie.

XSS stealing the refresh cookie: httpOnly prevents JavaScript from reading cookies. A network attacker needs more than an XSS payload.

Database breach: Token hashes are stored, not raw tokens. Rainbow tables do not work on 256-bit random values.

Token replay by attacker: Refresh token rotation with reuse detection means the first legitimate use invalidates the old token. If the attacker presents it later, the entire family is revoked and the user is forced to re-authenticate.

User needs instant revocation: revoked_at in the database is checked on every refresh. Logout is immediate for all future access.

Operational notes

Set a reasonable cleanup job. Tokens with revoked_at or expires_at in the past can be deleted after a retention window. A daily cron or a PostgreSQL pg_cron job keeps the table small.

DELETE FROM refresh_tokens
WHERE expires_at < now() - interval '30 days'
   OR revoked_at < now() - interval '30 days';

Monitor refresh failures. A sudden spike in 401s from /auth/refresh often means clients are sending expired cookies, which can happen after a deploy that changed the cookie signing or path. It can also indicate a bot trying stolen tokens.

Keep the refresh endpoint rate-limited per IP. An attacker with a leaked token hash (from logs, for example) should not be able to brute-force refresh attempts. Five attempts per minute is plenty for legitimate users.

Practical takeaway

JWTs are fine for authorization between services and for short-lived access tokens. They are terrible for session management because they cannot be revoked without giving up the stateless property that makes them appealing.

The production pattern is:

  1. Issue 5-minute JWT access tokens.
  2. Issue long-lived opaque refresh tokens in httpOnly, Secure, SameSite=Strict cookies.
  3. Rotate refresh tokens on every use.
  4. Detect reuse via the replaced_by chain and revoke the entire token family on theft.
  5. Store only SHA-256 hashes of refresh tokens.
  6. Give users explicit logout and logout-everywhere endpoints.

This is not more code than a naive JWT setup. It is roughly the same amount of code, but the security properties are completely different. A stolen token becomes a 5-minute incident instead of a 24-hour incident. A compromised account can be locked out in one database update. And the “stateless API” dream stays intact for the actual business endpoints, because access tokens are still verified without a database round-trip.


A note from Yojji

Secure session architecture sits at the intersection of backend infrastructure, security policy, and frontend engineering, exactly where small oversights turn into data breaches. Yojji helps teams build hardened web applications and APIs with senior-level engineers who treat authentication as a first-class system component, not an afterthought. If your team is moving from prototype to production and needs the session model to survive a security audit, Yojji is worth a conversation.