QA
Intermediate LevelExpress JS

How do you implement a secure JWT Refresh Token Rotation architecture in Express?

❓ Interview Prompt: Explain short-lived Access Tokens vs long-lived Refresh Tokens, HttpOnly cookie storage, Refresh Token Rotation, and Redis revocation.

Storing long-lived JWTs in localStorage exposes applications to token theft via XSS.

Refresh Token Rotation Architecture:

1
Short-Lived Access Token (15 min): Sent in JSON body, used for REST API requests.
2
Long-Lived Refresh Token (7 days): Stored in an HttpOnly, Secure cookie and recorded in Redis.
3
Rotation: When refreshing, verify the Refresh Token, delete it from Redis, issue a brand new Access + Refresh Token pair, and update the cookie! If a reused token is presented, revoke all user tokens immediately (detects theft attempts).

Code Implementation Example

javascript
import express from 'express';
import jwt from 'jsonwebtoken';

const app = express();

app.post('/api/auth/refresh', async (req, res) => {
  const refreshToken = req.cookies.refreshToken;
  if (!refreshToken) return res.status(401).json({ error: 'Refresh token missing' });

  // 1. Verify token & check if present in Redis whitelist
  const isTokenValid = await redis.sismember('valid_refresh_tokens', refreshToken);
  if (!isTokenValid) return res.status(403).json({ error: 'Token revoked or reused' });

  // 2. Rotate token: Delete old token from Redis!
  await redis.srem('valid_refresh_tokens', refreshToken);

  // 3. Issue new pair
  const newAccessToken = jwt.sign({ userId: 1 }, 'access-secret', { expiresIn: '15m' });
  const newRefreshToken = jwt.sign({ userId: 1 }, 'refresh-secret', { expiresIn: '7d' });
  await redis.sadd('valid_refresh_tokens', newRefreshToken);

  res.cookie('refreshToken', newRefreshToken, { httpOnly: true, secure: true });
  res.json({ accessToken: newAccessToken });
});
💡Implementing JWT Refresh Token Rotation with HttpOnly cookies and Redis.
🎯 Interview Key Takeaway

Use short-lived Access Tokens and rotate long-lived Refresh Tokens stored in HttpOnly cookies with Redis revocation tracking.

#JWT#Refresh Token#Security#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?