Refresh token rotation in Express + TypeScript, explained (with a free boilerplate)
Most Express auth tutorials stop at "sign a JWT, put it in a header, done." That works until you need to log someone out, or until a token leaks. Then you discover a JWT can't be revoked.
In this post I'll walk through the pattern I use instead: short-lived access tokens + rotating refresh tokens with reuse detection. All the code comes from an open-source starter I published, linked at the end.
The problem with long-lived JWTs
A JWT is valid until it expires. The server doesn't keep a list of them, which is the whole point: no database lookup per request. That also means:
- You can't log a user out of other devices.
- If a token is stolen, the attacker keeps access until it expires.
- Making it expire in 15 minutes fixes that, but now users log in every 15 minutes.
The fix: two tokens with two jobs
| Access token | Refresh token | |
|---|---|---|
| Format | JWT | Random opaque string |
| Lifetime | 15 minutes | 30 days |
| Stored on server | No | Yes, hashed |
| Sent on | Every API request | Only to /auth/refresh |
| Revocable | No (but expires fast) | Yes |
The access token keeps requests fast. The refresh token is the revocable part, so it lives in the database. Why hash it? Same reason you hash passwords: if your database leaks, the attacker shouldn't get working sessions.
import { createHash, randomBytes } from "node:crypto";
export const randomToken = (bytes = 48) => randomBytes(bytes).toString("base64url");
export const sha256 = (v: string) => createHash("sha256").update(v).digest("hex");
SHA-256 is enough here (no bcrypt needed) because the token is 48 random bytes, not a guessable password.
Rotation: every refresh issues a new token
When the client calls /auth/refresh, we don't just return a new access token. We also revoke the refresh token it used and return a new one. Every login starts a family (a random id). All tokens rotated from that login share it:
await refreshTokens.create({
userId: user.id,
tokenHash: sha256(refreshToken),
family, // same for the whole login session
expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
});
Reuse detection: the part most tutorials skip
Here's the trick. After rotation, the old token is revoked. A legitimate client never sends a revoked token again, because it already has the new one. So if a revoked token shows up, someone copied it. We don't know if it's the attacker or the real user, so we kill the whole family:
async refresh(refreshToken: string) {
const record = await this.refreshTokens.findByHash(sha256(refreshToken));
if (!record) throw AppError.unauthorized("Invalid refresh token");
if (record.revokedAt) {
// Replay of an already-rotated token: assume theft.
await this.refreshTokens.revokeFamily(record.family);
throw AppError.unauthorized("Refresh token reuse detected; session revoked");
}
if (record.expiresAt.getTime() <= Date.now()) {
throw AppError.unauthorized("Refresh token expired");
}
const user = await this.users.findById(record.userId);
if (!user) throw AppError.unauthorized("Invalid refresh token");
await this.refreshTokens.revoke(record.id);
return this.issueTokens(user, record.family); // new access + new refresh
}
Both the attacker and the user get logged out of that session. The user logs in again; the attacker can't.
Logout becomes trivial. Logout: revoke the family of the refresh token. Logout everywhere: revoke every token for the user. Password change: revoke everything (whoever had the old password loses access).
Testing it without a database
The service only talks to a RefreshTokenRepository interface. In production it's MongoDB; in tests it's a Map. That makes the security tests fast and readable:
it("detects refresh token reuse and revokes the whole session", async () => {
const { refreshToken: stolen } = await registerUser();
const rotated = (await api.post("/api/auth/refresh").send({ refreshToken: stolen })).body.refreshToken;
// Attacker replays the old token -> rejected, and the session is killed.
await api.post("/api/auth/refresh").send({ refreshToken: stolen }).expect(401);
// The legitimate user's newer token no longer works either.
await api.post("/api/auth/refresh").send({ refreshToken: rotated }).expect(401);
});
The whole suite (17 tests) runs in about a second.
Two more details worth copying
Don't leak which emails exist. Return the same error for "wrong password" and "no such user", and compare against a dummy bcrypt hash when the user doesn't exist so the response time is the same.
Let MongoDB clean up for you. A TTL index on expiresAt deletes expired tokens automatically:
expiresAt: { type: Date, required: true, expires: 0 }
Get the full code
Everything above (plus roles, Zod validation, error handling, Docker and the tests) is in a free, MIT-licensed starter: 👉 github.com/baivoo28/express-saas-starter
Clone it, set one env var, run npm run dev. If you find something to improve in the auth flow, issues and PRs are welcome. A ⭐ helps other people find it.
Comments
No comments yet. Start the discussion.