4 min readNestJSPrismaPostgreSQL

Rotating refresh tokens without logging anyone out on a double click

Every refresh swaps the token, and reusing an old one ends the whole session. The catch: two tabs refreshing at once look like theft.

In Fiado, the loan and investment simulator we built as a team for a credit union, I owned sign-up and sessions. A session lives in two httpOnly cookies: an access token (a 15-minute JWT) and a 30-day refresh token to get a new one without typing the password again. The second one is what matters: whoever holds it keeps the account for a month.

Opaque, and only its fingerprint in the database

The refresh token is not a JWT: it is 32 random bytes. Its validity lives in an AuthSession row, not in the token, so it can really be revoked. The database stores its SHA-256, not the token: a leaked table would not let anyone in.

backend/src/common/tokens.ts
export const newRefreshToken = () => randomBytes(32).toString('base64url');

export const hashRefreshToken = (token: string) =>
  createHash('sha256').update(token).digest('hex');

And the cookie is only sent to /api/auth: the browser doesn't even attach it to the rest of the API.

backend/src/modules/auth/cookies.ts
const REFRESH_PATH = '/api/auth';

response.cookie(REFRESH_COOKIE, tokens.refreshToken, {
  ...base(),
  path: REFRESH_PATH,
  maxAge: refreshTtlSeconds() * 1000,
});

Every refresh replaces it

On refresh, the used token is marked (rotatedAt) and a new one is issued in the same family (familyId: one per sign-in). Each token works once. If one that was already used shows up, someone else has a copy: the owner or a thief, and the server can't tell which. So it revokes the whole family and both have to sign in again. A stolen cookie doesn't survive its owner's next refresh.

backend/src/modules/auth/auth.service.ts
if (session.rotatedAt || session.revokedAt) {
  await this.revokeFamily(session.familyId);
  throw new UnauthorizedException(
    'Sesión revocada: ese token de renovación ya había sido usado',
  );
}

The catch: two tabs at once

If two requests refresh with the same token at almost the same time (two tabs, a double click, a retry), both read it as valid. The second one to write would find it already rotated and, under the rule above, would end the session of someone who did nothing wrong.

So the token isn't marked by reading and then writing, but with a single write conditioned on its state:

backend/src/modules/auth/auth.service.ts
const { count } = await this.prisma.authSession.updateMany({
  where: { id: session.id, rotatedAt: null, revokedAt: null },
  data: { rotatedAt: new Date() },
});
if (count === 0) throw new UnauthorizedException(INVALID_SESSION);

return this.issueSession(session.user, session.familyId, context);

The database picks the winner: only one of the two writes finds the row unrotated. The loser gets a 401 and revokes nothing; the new cookie the winner set works for both tabs. The theft alarm only fires when the token was already rotated when read, not on a tie.

What I take from it

A security rule that punishes reuse has to tell reuse apart from concurrency. That can't be done in the application with two queries in a row: it has to be left to the database, in one atomic write.