← Back to Node.js, page 8

nodejs-0158 · Hard senior

How do refresh tokens work, and how does rotation with reuse detection protect against token theft?

A short-lived access token is used on every request, and a long-lived refresh token only to get new access tokens. With rotation, each refresh returns a new refresh token and invalidates the old one. If an old token is used again, someone has a copy, so the server revokes the whole token family and forces a new login. Store only hashes of refresh tokens and bind them to a family and device.

Full answer

Why two tokens

  • Access token: 5 to 15 minutes, sent with every API call. If stolen, the damage window is short.
  • Refresh token: days or weeks, kept safer (HttpOnly cookie or secure storage), sent only to the refresh endpoint.

Rotation

  • POST /refresh with the current refresh token. The server checks it, marks it used, creates a new refresh token in the same family and returns a new access token and the new refresh token.
  • The old refresh token never works again.

Reuse detection

  • If an attacker steals a refresh token and uses it, the real user's next refresh presents an already used token (or the attacker's later one does). Either way a used token arrives again.
  • The server treats this as theft and revokes the entire family. Both people lose access, and the user must log in again. This limits damage for the price of one extra login.
  • Allow a short grace window (a few seconds) for legitimate races, such as two tabs refreshing together, or answer both with the same new token.

Storage and design

  • Store a hash of the refresh token (SHA-256 is fine because the token is random and long), not the token itself. Record user, family id, expiry, used flag, device and creation time.
  • Use cryptographically random tokens (crypto.randomBytes(32)), not JWTs, so the server controls state.
  • Absolute lifetime for the family (for example 30 days) plus idle expiry.
  • Logout revokes the family. Password change revokes all families of the user.
  • For browsers use cookies with HttpOnly, Secure and SameSite, and protect the refresh endpoint from CSRF.
javascript
const crypto = require('node:crypto');

const sha256 = (text) => crypto.createHash('sha256').update(text).digest('hex');
const tokens = new Map();                 // hash -> { user, family, used, revoked }
const families = new Map();               // family -> { revoked }
let counter = 0;

function issue(user, family = 'fam-' + ++counter) {
  const token = crypto.randomBytes(24).toString('base64url');
  tokens.set(sha256(token), { user, family, used: false });
  if (!families.has(family)) families.set(family, { revoked: false });
  return token;
}

function refresh(token) {
  const record = tokens.get(sha256(token));
  if (!record) return { error: 'unknown token' };
  if (families.get(record.family).revoked) return { error: 'family revoked, log in again' };
  if (record.used) {                                           // a used token came back: someone has a copy
    families.get(record.family).revoked = true;
    return { error: 'reuse detected, family revoked' };
  }
  record.used = true;
  return { accessToken: 'access-for-' + record.user, refreshToken: issue(record.user, record.family) };
}

const first = issue('asha');                                    // issued at login
const step1 = refresh(first);
console.log('1. refresh with token 1 ->', step1.accessToken ? 'new access + new refresh token' : step1.error);

const step2 = refresh(step1.refreshToken);
console.log('2. refresh with token 2 ->', step2.accessToken ? 'new access + new refresh token' : step2.error);

// An attacker who copied token 1 earlier now tries it.
console.log('3. attacker replays token 1 ->', refresh(first).error);
console.log('4. the real user uses token 3 ->', refresh(step2.refreshToken).error);

console.log('stored values are hashes, not tokens:', ![...tokens.keys()].includes(first));
console.log('tokens kept for this family:', tokens.size);

The attacker replays the first refresh token after the user has already rotated it. The server detects the reuse and revokes the family, so even the newest token stops working. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. refresh with token 1 -> new access + new refresh token 2. refresh with token 2 -> new access + new refresh token 3. attacker replays token 1 -> reuse detected, family revoked 4. the real user uses token 3 -> family revoked, log in again stored values are hashes, not tokens: true tokens kept for this family: 3

Key points

  • Short access tokens limit the damage of theft.
  • Rotation gives a new refresh token on every use.
  • Reuse of a used token revokes the whole family.
  • Store hashes of random tokens, not the tokens.
  • Logout and password change revoke families.

Common mistakes

  • Reusing the same refresh token forever.
  • Storing refresh tokens in plain text in the database.
  • No family concept, so a theft cannot be detected.
  • Treating a double refresh from two browser tabs as theft with no grace window.
  • Making the refresh token a long-lived JWT that cannot be revoked.

Follow-ups

  • How do you handle two tabs refreshing at the same time?
  • Where should a single page app keep the refresh token?
  • What do you do on password change?

Tips

  • Explain access versus refresh first.
  • Say 'family' and 'reuse'.
  • Mention hashing the stored token.