Why long-lived refresh tokens get rotated on every use, how token families let you spot a stolen token, what to do about concurrent refreshes, and a TypeScript example on Encore with Postgres.

Short-lived access tokens stop working minutes after they leak. The refresh token that mints them lives for weeks, sits in a cookie or on a phone, and gives an attacker fresh access tokens for as long as it stays valid.
Rotation makes each refresh token single use and ties it to a family that can be revoked as a unit. This guide covers the mechanics, concurrent requests and a TypeScript implementation on Postgres.
At login the server issues a short-lived access token (often a JWT that expires in 15 minutes) and an opaque refresh token. When the access token expires, the client sends the refresh token, and the server returns a new access token and a new refresh token while marking the old refresh token as used. RFC 9700, the OAuth 2.0 Security Best Current Practice, lists rotation as one of two accepted ways to protect refresh tokens issued to public clients such as browsers and mobile apps.
Store refresh tokens as SHA-256 hashes, like any other bearer credential, and keep the raw value only in the client. In browsers, an HttpOnly, Secure cookie scoped to the refresh path, set as described in the MDN Set-Cookie reference, keeps it away from JavaScript and from every request that does not need it.
Every token minted from one login shares a family ID. If an attacker copies a refresh token and uses it first, the legitimate client later presents the same, now spent, token. If the client uses it first, the attacker is the one holding a spent token. Either way the server sees a used token come back, cannot tell which copy belongs to the user, and revokes the entire family, which logs out the attacker and forces the user to sign in again.
The security benefit depends on two rules: the reuse check must run on every refresh and the revocation must cover all tokens in the family, including the newest one.
Two browser tabs, or a mobile app that fires several requests when it wakes up, can refresh at the same moment with the same token. The first wins, the second looks like reuse and the user is logged out for no reason. There are three common answers: serialize refreshes on the client (a single in-flight refresh promise shared by all callers), allow a short grace window of a few seconds in which the previous token still returns the already-issued successor, or both. Client-side serialization is the simpler fix and keeps the server rule strict.
Use two clocks for the refresh token, the idle and absolute timeouts described in the OWASP Session Management Cheat Sheet. An idle timeout (for example 14 days) means a session nobody uses expires, and an absolute lifetime (for example 60 days from login) means even an active session ends eventually. Store the family's login time and refuse to rotate past the absolute limit. Logging out revokes the family, and a password reset should revoke every family for that user.
Encore is a backend framework with built-in infrastructure, which here means the token table, the signing key and the auth check live in one TypeScript service with nothing to wire up between them. Refresh tokens are stored in an Encore Postgres database, the JWT signing key is an Encore secret, and an auth handler verifies access tokens for every authenticated endpoint in the app.
Run in your terminal to get started locally.
-- auth/migrations/1_create_refresh_tokens.up.sql
CREATE TABLE refresh_tokens (
token_hash TEXT PRIMARY KEY,
family_id UUID NOT NULL,
user_id BIGINT NOT NULL,
family_started TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ
);
CREATE INDEX refresh_tokens_family ON refresh_tokens (family_id);
CREATE INDEX refresh_tokens_user ON refresh_tokens (user_id);
// auth/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("auth");
// auth/tokens.ts
import { api, APIError, Gateway, Header } from "encore.dev/api";
import { authHandler } from "encore.dev/auth";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { secret } from "encore.dev/config";
import log from "encore.dev/log";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { SignJWT, jwtVerify } from "jose";
const db = new SQLDatabase("auth", { migrations: "./migrations" });
const signingKey = secret("JWTSigningKey");
const key = () => new TextEncoder().encode(signingKey());
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
interface TokenPair {
accessToken: string;
refreshToken: string;
}
async function accessToken(userId: number): Promise<string> {
return new SignJWT({})
.setProtectedHeader({ alg: "HS256" })
.setSubject(String(userId))
.setIssuedAt()
.setExpirationTime("15m")
.sign(key());
}
// Called by the login endpoint once the user's credentials are checked.
export const startSession = api(
{ expose: false },
async ({ userId }: { userId: number }): Promise<TokenPair> => {
const refreshToken = randomBytes(32).toString("base64url");
await db.exec`
INSERT INTO refresh_tokens (token_hash, family_id, user_id, family_started, expires_at)
VALUES (${sha256(refreshToken)}, ${randomUUID()}::uuid, ${userId}, now(), now() + interval '14 days')`;
return { accessToken: await accessToken(userId), refreshToken };
},
);
export const refresh = api(
{ expose: true, method: "POST", path: "/auth/refresh" },
async ({ refreshToken }: { refreshToken: string }): Promise<TokenPair> => {
await using tx = await db.begin();
const row = await tx.queryRow<{
family_id: string;
user_id: number;
used: boolean;
revoked: boolean;
expired: boolean;
}>`
SELECT family_id::text, user_id,
used_at IS NOT NULL AS used,
revoked_at IS NOT NULL AS revoked,
expires_at < now() OR family_started < now() - interval '60 days' AS expired
FROM refresh_tokens WHERE token_hash = ${sha256(refreshToken)}
FOR UPDATE`;
if (!row || row.revoked || row.expired) throw APIError.unauthenticated("sign in again");
if (row.used) {
await tx.exec`
UPDATE refresh_tokens SET revoked_at = now()
WHERE family_id = ${row.family_id}::uuid AND revoked_at IS NULL`;
await tx.commit();
log.warn("refresh token reuse, family revoked", { familyId: row.family_id, userId: row.user_id });
throw APIError.unauthenticated("sign in again");
}
const next = randomBytes(32).toString("base64url");
await tx.exec`UPDATE refresh_tokens SET used_at = now() WHERE token_hash = ${sha256(refreshToken)}`;
await tx.exec`
INSERT INTO refresh_tokens (token_hash, family_id, user_id, family_started, expires_at)
SELECT ${sha256(next)}, family_id, user_id, family_started, now() + interval '14 days'
FROM refresh_tokens WHERE token_hash = ${sha256(refreshToken)}`;
await tx.commit();
return { accessToken: await accessToken(row.user_id), refreshToken: next };
},
);
export const logout = api(
{ expose: true, method: "POST", path: "/auth/logout" },
async ({ refreshToken }: { refreshToken: string }): Promise<void> => {
await db.exec`
UPDATE refresh_tokens SET revoked_at = now()
WHERE family_id = (SELECT family_id FROM refresh_tokens WHERE token_hash = ${sha256(refreshToken)})
AND revoked_at IS NULL`;
},
);
interface AuthParams {
authorization: Header<"Authorization">;
}
interface AuthData {
userID: string;
}
export const auth = authHandler<AuthParams, AuthData>(async ({ authorization }) => {
const token = authorization?.replace(/^Bearer /, "") ?? "";
try {
const { payload } = await jwtVerify(token, key(), { algorithms: ["HS256"] });
return { userID: payload.sub! };
} catch {
throw APIError.unauthenticated("invalid or expired access token");
}
});
export const gateway = new Gateway({ authHandler: auth });
The FOR UPDATE lock means two refreshes with the same token are serialized in the database: the second one waits, then sees used and revokes the family, which is exactly the reuse rule. If your clients cannot serialize refreshes, that is the place to add a short grace window. Set the key with encore secret set --type dev,local JWTSigningKey and separately for production, using at least 32 random bytes.
encore run starts Postgres locally, so you can test the reuse path by calling /auth/refresh twice with the same token and watching the second call revoke the family in the local trace. The log.warn line on reuse is worth alerting on, since a steady trickle of it usually means a client bug and a spike usually means stolen tokens.
The schema and the rotation logic sit in one file, so an agent asked to add "log out all devices" or a grace window changes the query and the table together and can replay the token sequence locally to check it.
Best fit: Apps that issue their own access tokens and want rotation, reuse detection and revocation backed by their own Postgres database.
Every time a client uses a refresh token to get a new access token, the server also issues a new refresh token and invalidates the old one. A refresh token therefore works exactly once, which turns a stolen token into something the server can detect.
All tokens issued from one login share a family ID. If a token that was already used is presented again, either the client or an attacker holds a stale copy, so the server revokes every token in the family and the user has to sign in again.
A common setup is a 15-minute access token, a refresh token that expires after 7 to 30 days of inactivity, and an absolute session lifetime of 30 to 90 days after which the user signs in again regardless of activity.
Store hashed refresh tokens with a family ID in an Encore Postgres database, rotate them inside a transaction that locks the presented row, and verify the short-lived access token in an Encore auth handler. Reuse of a spent token revokes the whole family.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.