Picture a refresh token ending up somewhere it shouldn't: a HAR file attached to a bug report, a verbose proxy log, a browser profile copied by malware. Nobody notices. The user keeps working, and so does whoever holds the copy. Every few minutes both of them trade the same bytes for a fresh access token, and the server can't tell them apart, because there is nothing to tell apart. It's one token.
Refresh token rotation and reuse detection exist for exactly that. Here's how the auth service of a platform of thirteen NestJS services does it, read straight from the repository: one row per login, one conditional UPDATE per refresh, and one rule that turns a replayed token into an alarm. Plus the places where it still leaks.
Why is a stolen refresh token worse than a stolen access token?
Because of what each one is for.
An access token is shown to every service on every request, so it's built to be worth little: here it's a JWT that expires after 15 minutes by default (configurable up to an hour). Steal one and you get a quarter of an hour.
A refresh token is shown to exactly one endpoint, and its only job is to mint new access tokens. Steal one and you hold the session itself for as long as the refresh token lives. In the repository the refresh window is an idle timeout: 30 minutes by default, configurable up to 90 days. On a deployment that raises it for "remember me", a copied token means months of access.
And using it looks normal. No password, no login alert: the thief calls the same endpoint the user's browser calls.
Why use two tokens with two lifetimes?
Here's the analogy I'll carry through the rest of the article: a metro system with single-use tickets.
The access token is the stamped slip you show inspectors on the train. It's short-lived, shown to everyone and cheap to lose.
The refresh token is the ticket you feed into one gate to get a new slip. You never show it to inspectors. In the browser that's literally true: the cookie is scoped to the auth routes, so it never travels anywhere else.
Two tokens let you put the exposure on the cheap one and the lifetime on the guarded one.
Is the access token really stateless?
Not here. The access token carries a session id claim, sid. To authenticate a request, the auth service verifies the JWT signature and then loads the session row by sid. It rejects the token if the session is revoked or expired, the account is locked or disabled, or the user's roles changed after issue. No other service verifies the JWT itself; the ones that authenticate users ask the auth service over gRPC, with a deadline on the call (the article on REST, gRPC and Kafka explains why that matters).
So revoking a session cuts off its access tokens on the next request, not 15 minutes later. Reuse detection depends on that.
What is refresh token rotation?
Start with the version most tutorials ship. The refresh token is a long random string stored on the user row and valid until it expires. Every refresh returns a new access token and keeps the same refresh token.
In metro terms, that's a ticket the gate hands back after reading it. Whoever photocopies it rides for as long as the original works.
Rotation changes one rule: the gate keeps your ticket and prints you a new one. Every successful refresh invalidates the presented token and returns a fresh one. A stolen copy now works only until the next time either party uses it.
Why isn't rotation alone enough?
Here's the trap. Suppose the gate only remembers the current ticket:
// Naive rotation: read, check, write.
const session = await db.session.findUnique({ where: { tokenHash: presentedHash } });
if (!session || session.revokedAt || session.expiresAt <= now) {
throw new UnauthorizedException();
}
await db.session.update({
where: { id: session.id },
data: { tokenHash: nextHash },
});Walk through a theft. The thief refreshes first, so the user's ticket now matches nothing. The user's next refresh fails as "invalid", they sign in again and get a new session. The thief keeps the old one.
So rotation without memory doesn't detect anything. It picks a winner, and the winner is whoever refreshes first. The loser gets the same generic error as a token that simply expired.
There's a second bug: the code reads, then writes. Two requests carrying the same token can both pass the check before either one writes, and both get a valid-looking response. You've just forked a session you thought was linear.
How does reuse detection catch a stolen token?
Give the gate a memory of exactly one thing: the last ticket it swallowed.
Each session row stores two hashes: tokenHash, the current one, and previousTokenHash, the one just rotated out. A presented token can now be in one of three states:
| Presented token matches | Meaning | Response |
|---|---|---|
tokenHash |
the normal case | rotate, return a new token |
previousTokenHash |
a spent ticket is being replayed | revoke the session, 401 |
| neither | unknown or long gone | 401, nothing else |
Replay the theft. The thief refreshes first and gets a new ticket. The user's next refresh presents what is now previousTokenHash. A swallowed ticket showing up again means two people held copies, and the server has no way to know which one is honest. So it doesn't try: it revokes the whole session. The user has to log in again, and this time the thief is locked out too, because their shiny new token belongs to a revoked session. Reverse the order and you get the same result. Whoever comes second trips the alarm.
That's the core idea: the theft becomes detectable the moment both copies are used.
Why revoke the whole session, not just the token?
Because you can't tell who's who. Reject only the replayed token and you've blessed whoever got there first, possibly the thief. Revoking the session is the only response that's correct in both orders, and since access tokens are checked against the session row, it also ends any access token the thief already holds. One login is one row, so this ends that device's session, not every session the user has.
How do you rotate safely under concurrency?
Now fix the race. Rotation must be a compare-and-swap: replace the hash only if it's still the one I was given. In SQL:
UPDATE refresh_session
SET token_hash = $2, -- next hash
previous_token_hash = $3, -- presented hash
last_seen_at = now(),
expires_at = now() + interval '30 minutes'
WHERE id = $1
AND token_hash = $3
AND revoked_at IS NULL
AND expires_at > now();If two requests run this at the same moment with the same token, Postgres serializes them on the row lock. Under the default READ COMMITTED level, the second UPDATE waits, then re-checks its WHERE clause against the row the first one committed. token_hash no longer matches, so it updates zero rows. Exactly one caller wins, with no explicit lock and no retry loop. It's the same trick as the version column in idempotency keys and optimistic locking.
Here's the repository's version with Prisma, lightly renamed:
type RotationOutcome =
| { readonly kind: 'success' }
| { readonly kind: 'invalid' }
| { readonly kind: 'reused' };
export function rotateRefreshSession(input: RotateInput): Promise<RotationOutcome> {
return prisma.$transaction(async (tx): Promise<RotationOutcome> => {
const rotation = await tx.refreshSession.updateMany({
where: {
id: input.sessionId,
tokenHash: input.presentedHash,
revokedAt: null,
expiresAt: { gt: input.now },
},
data: {
tokenHash: input.nextHash,
previousTokenHash: input.presentedHash,
lastSeenAt: input.now,
expiresAt: input.idleExpiresAt,
},
});
if (rotation.count === 1) return { kind: 'success' };
const latest = await tx.refreshSession.findUnique({
where: { id: input.sessionId },
select: { previousTokenHash: true, revokedAt: true, expiresAt: true },
});
const replayedSpentToken =
latest?.previousTokenHash === input.presentedHash &&
latest.revokedAt === null &&
latest.expiresAt > input.now;
if (!replayedSpentToken) return { kind: 'invalid' };
await tx.refreshSession.updateMany({
where: { id: input.sessionId, revokedAt: null },
data: { revokedAt: input.now },
});
return { kind: 'reused' };
});
}updateMany is deliberate: Prisma's update needs a unique where and throws when nothing matches, while updateMany takes the extra conditions and returns a count. That count is the compare-and-swap result.
The zero-row branch matters as much as the success branch. Lose the race and find your token in previousTokenHash: someone rotated it a moment ago, so that's reuse. Find it nowhere: it's just invalid. Both return 401 with different error codes, so a client can tell "your session was ended for safety" from "please log in".
The service also checks before rotating: its lookup matches either hash, and a hit on the previous one goes straight to revocation. The conditional update is the backstop for a replay and a rotation that land at the same instant.
How should you store refresh tokens on the server?
Hashed, like a password, but with a different kind of hash:
import { createHash, randomBytes } from 'node:crypto';
const REFRESH_TOKEN_BYTES = 32;
export function generateRefreshToken(): string {
return randomBytes(REFRESH_TOKEN_BYTES).toString('base64url');
}
export function hashRefreshToken(token: string): string {
return createHash('sha256').update(token, 'utf8').digest('hex');
}Thirty-two random bytes are 256 bits of entropy, which base64url turns into 43 characters. Only the SHA-256 hex digest goes into the database, so a leaked backup of the session table contains nothing you could present at the gate.
Why not bcrypt or Argon2? Slow hashes protect low-entropy secrets: humans pick guessable passwords, so you make each guess expensive. Nobody guesses 256 random bits. A slow hash is also salted, so you can't look a row up by it. SHA-256 is deterministic, so token_hash gets a unique index and each lookup is one index probe; previous_token_hash gets a plain index. The rest of the row is boring on purpose: user id, expires_at, revoked_at, last_seen_at and some masked device metadata.
Cookie or localStorage: where should the refresh token live?
In the browser, the refresh token never touches JavaScript. It's set like this (name shortened):
Set-Cookie: __Secure-refresh=<token>; HttpOnly; Secure; SameSite=Lax; Path=/api/v1/auth; Max-Age=1800Each attribute does one job:
HttpOnly: scripts can't read it, so an XSS bug can't exfiltrate it.Secureand the__Secure-prefix: HTTPS only, and the browser refuses the cookie ifSecureis missing.SameSite=Lax: the cookie isn't attached to cross-site POSTs, so another site can't trigger a refresh. Note that "same-site" is wider than "same-origin": a sibling subdomain counts as the same site.Path=/api/v1/auth: it's sent only to the auth routes, never to the rest of the API. That's the "shown at one gate only" rule, enforced by the browser.Max-Age: matches the idle window and is re-issued on every rotation.
The refresh endpoint reads the token only from the cookie, and the response body holds just access_token and expires_in. The web client keeps the access token in memory, never in localStorage. On page load it simply calls refresh.
localStorage would be simpler, and readable by any script on your origin, including one smuggled in through a dependency. Keeping the long-lived secret out of script reach is why I accept the cookie's complexity: CORS with credentials, SameSite and the domain all have to be right, or the cookie quietly isn't sent. The repository's decision record says it plainly: the cookie configuration exists in code, but browser behaviour over HTTPS is unverified.
Why do two browser tabs log the user out?
Open the app in two tabs at the same moment, for example when the browser restores your last session. Each tab boots with no access token in memory and calls refresh, and since the cookie jar is shared, both requests carry the same refresh token.
Tab A wins the conditional update. Tab B's matches zero rows, finds its token in previousTokenHash, and revokes the session. The user did nothing wrong and is logged out of both tabs.
In metro terms, two family members walked through two gates in the same second with the same ticket. The gates can't know they're family.
The web client in the repository already prevents this inside one tab. Concurrent callers share one pending refresh promise instead of each calling the endpoint (plus a generation counter, so a refresh that finishes after logout is thrown away). Stripped down:
let pendingRefresh: Promise<string | null> | null = null;
export function refreshOnce(): Promise<string | null> {
pendingRefresh ??= requestNewAccessToken().finally(() => {
pendingRefresh = null;
});
return pendingRefresh;
}It doesn't coordinate across tabs. The fix I'd reach for is the Web Locks API, which serializes work across all tabs of one origin:
export function refreshAcrossTabs(): Promise<string | null> {
return navigator.locks.request('auth-refresh', () => refreshOnce());
}Tab B now waits for A. When its turn comes, the cookie jar already holds A's new token, so B's refresh is a legitimate rotation, not a replay.
The other common fix is a server-side grace window that accepts the previous token for a few seconds. I'd avoid it here. A thief replaying inside the window passes too, and since only hashes are stored, the server can't hand back the token it already issued. It would have to mint a second one, forking the session into two live branches that a one-current, one-previous row can't represent.
A lost response produces the same false positive with a single tab. The server rotates, the network drops the response along with its Set-Cookie, and the next refresh (a retry or a page reload) presents the old token. That is reuse by definition. It's the same "did my request happen?" problem from the idempotency article, and here I chose the safe failure: log the user out rather than risk keeping a thief in.
What doesn't rotation solve?
XSS that rides the live session. HttpOnly stops a script from reading the refresh token. It doesn't stop a script running on your origin from calling the refresh endpoint and using the access token that comes back. Nothing is replayed, so nothing trips the alarm. Rotation protects against stolen copies, not against a compromised page.
A thief who rotates twice while you're away. The gate remembers one ticket. If the user closes the laptop and the thief refreshes twice, the user's token is now two generations old. It matches neither hash, so it's merely "invalid". The user logs in again and gets a new session while the thief's session lives on. Detection only works if the honest copy is used within one rotation of the stolen one.
A session that never ends. Every rotation pushes expires_at forward by the idle window, and I found no absolute lifetime in the session code. A client that refreshes on schedule keeps the same session indefinitely, and so does a quiet thief.
A silent alarm. Logout revokes the session and writes a session-revoked event through the transactional outbox in the same transaction. The reuse path writes no event, and nothing in the repository consumes that event yet anyway. The most interesting security signal the system produces ends as a 401 and a log line.
What does this design cost?
- A database read per authenticated request, plus a gRPC hop for services that ask the auth service. That's the price of revocation that takes effect immediately instead of up to 15 minutes later.
- A write per refresh for every active client, roughly once per access-token lifetime.
- False logouts from tab races and lost responses, which is why the reuse error deserves its own code and its own message.
- Cookie plumbing. CORS with credentials,
SameSite, domains and HTTPS must line up in every environment, and the failure mode is a cookie that silently isn't sent.
What would I do differently?
Remember the whole family, not one generation. Keep one row per issued token with its session id and a spent_at timestamp, kept for the life of the session. Then any old token counts as reuse, and the thief-rotates-twice case becomes detectable. The OAuth security best current practice, RFC 9700, lays out the same reasoning: when an invalidated refresh token shows up, the server can't tell which party sent it, so it revokes the active one.
Add an absolute lifetime on top of the idle window, so even a perfectly quiet thief eventually has to log in.
Make reuse loud. Emit the same session-revoked event on reuse as on logout, with a different reason, and tell the user something like "this session was ended because the same sign-in was used in two places."
Serialize refresh across tabs from day one. A few lines of client code remove the most common false positive.
Test the cookie in real browsers (same-site and cross-site over HTTPS: refresh, reuse, logout) before calling it done. Configuration in code proves intent, not that a browser honours it.
Key takeaways
- A refresh token is the session. Show it to one endpoint only, keep it out of JavaScript, and store only its hash.
- Rotation without memory just picks a winner. Remember the previous hash and treat a replay as theft: revoke the session, because you can't tell who's honest.
- Rotate with a conditional
UPDATE ... WHERE token_hash = <presented>and check the row count. That's what makes concurrent refreshes safe. - Use a fast hash such as SHA-256 for 256-bit random tokens. Slow, salted hashes are for human passwords.
- Expect false positives from tabs and lost responses, and fix the tab race on the client with a cross-tab lock.
- Know the limits: one generation of memory, no absolute lifetime and a silent alarm are the gaps I'd close first.
Sessions are the last piece of application logic in this series. The final decision is where all thirteen services actually run: Docker Compose on one host, or Kubernetes.