A JSON Web Token is fast to check because nobody has to look anything up: the signature and the expiry time are in the token. That is also its problem. Once issued, it stays valid until it expires, even after the user logs out, changes their password, or has their account disabled. The standard answer is to split the job between two tokens: a short-lived access token that APIs check on every request, and a long-lived refresh token that only the auth server ever sees, used to get new access tokens without asking the user to sign in again.
This article builds that design end to end: the auth server, the database, the resource server, and the client, including the parts most tutorials skip, such as refresh token rotation, detecting stolen tokens, and two browser tabs refreshing at the same moment. Everything was tested on PostgreSQL 18 with the jose library on Node.js 24.
The short answer#
Two tokens, two jobs#
| Access token | Refresh token | |
|---|---|---|
| Purpose | Call APIs | Get new access tokens |
| Format | Signed JWT (self-contained) | Random opaque string (a database reference) |
| Lifetime | 5–15 minutes | Days or weeks, with an idle and an absolute limit |
| Sent to | Every API, on every request | Only the auth server’s token endpoint |
| Checked by | Signature and claims; no lookup | A database lookup, every time |
| Revocable | No: it expires | Yes, immediately |
| If stolen | Useful until it expires | Detected on reuse, when rotation is on |
The split works because the two tokens have opposite strengths. The access token is cheap to check and travels everywhere, so it must not be worth much for long. The refresh token is worth a lot, so it travels almost nowhere and is checked against the database, where it can be revoked at any moment.
Why access tokens must be short-lived#
A resource server that checks a JWT with a public key has no way to know that the session behind it has ended. Our test signed a user in, called “log out everywhere”, and then tried both tokens. The refresh token was refused immediately. The access token still worked and kept working until its exp claim had passed: with a 10-minute lifetime and the 30 seconds of clock tolerance the API allows, it was accepted at 629 seconds and rejected at 631 seconds.
That window is the whole cost of stateless tokens, and the access token’s lifetime is the only thing that bounds it. A stolen access token, a fired employee’s session, or a revoked permission stays usable for up to one lifetime. At 10 minutes, that is usually acceptable. At 24 hours, which is common in tutorials, it isn’t. (For the internals of verifying JWTs safely, see our JWT architecture guide.)
Choosing the lifetime#
Shorter is safer, but every expiry means a refresh, and every refresh is a database write. For a million active sessions, each refreshing once per access-token lifetime:
| Access token lifetime | Refreshes per second (1 million active sessions) | Longest a revoked session keeps API access |
|---|---|---|
| 5 minutes | 3,333 | 5 minutes, plus clock tolerance |
| 10 minutes | 1,667 | 10 minutes, plus clock tolerance |
| 15 minutes | 1,111 | 15 minutes, plus clock tolerance |
| 60 minutes | 278 | 60 minutes, plus clock tolerance |
The refresh endpoint below handled 4,081–4,122 rotations a second against a single PostgreSQL 18 instance in our test, with 20 connections, so even 5-minute tokens for a million active users fit on modest hardware. Only active sessions refresh: a user who closes the app stops refreshing and costs nothing. Meanwhile, checking an access token costs no database work at all: about 9,600–10,000 ES256 verifications a second on one CPU core. That asymmetry is the design working as intended. The expensive, revocable check happens every few minutes per user; the cheap, stateless one happens on every request.
Five to fifteen minutes is the usual range. Go shorter for high-risk operations (or require a fresh sign-in for them), and don’t go much longer: past an hour, the revocation window starts to matter more than the saved refreshes.
What a refresh token should be#
- Opaque and random. 32 bytes from a cryptographically secure generator, encoded as base64url. The auth server must look it up anyway to check for revocation, so a JWT would only add size and the temptation to trust it without the lookup.
- Stored as a hash. If the database leaks, hashes can’t be used to refresh anything. Plain SHA-256 is right here, not a password hash like Argon2: the token has 256 bits of randomness, so there is nothing to guess. Our password vs. integrity hashing article explains the difference.
- Grouped in families. Every login starts a family; every rotation adds a token to it. Revoking the family revokes the session, on that device only.
- Two lifetimes. An idle limit (here 7 days) ends sessions nobody uses, and an absolute limit (here 30 days) ends every session eventually, however active, so a stolen session can’t be kept alive forever.
-- schema.sql: refresh tokens are stored only as SHA-256 hashes, grouped in families: one family per login.
CREATE TABLE refresh_families (
id uuid PRIMARY KEY DEFAULT uuidv7(),
user_id bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, -- absolute lifetime: after this, the user signs in again
revoked_at timestamptz,
revoked_why text
);
CREATE TABLE refresh_tokens (
hash bytea PRIMARY KEY CHECK (octet_length(hash) = 32),
family_id uuid NOT NULL REFERENCES refresh_families ON DELETE CASCADE,
issued_at timestamptz NOT NULL DEFAULT now(),
idle_expires_at timestamptz NOT NULL, -- unused this long, and the session ends
used_at timestamptz -- set exactly once; a second use is a replay
);
CREATE INDEX ON refresh_tokens (family_id);
CREATE INDEX ON refresh_families (user_id) WHERE revoked_at IS NULL;uuidv7() is new in PostgreSQL 18: time-ordered IDs that keep the index compact, as our UUID v4 vs. v7 article measures.
Rotation and reuse detection#
With rotation, a refresh token can be used only once: each refresh returns a new access token and a new refresh token, and marks the old one as used. That turns a stolen refresh token into something detectable. If an attacker copies a refresh token, then either the attacker or the real user will use it second, and a second use of a spent token is exactly what the server watches for. When it sees one, it revokes the whole family: the copy and every token issued after it stop working. The current OAuth 2.0 security best practice (RFC 9700) recommends rotation, or tokens bound to the client’s key, for clients that can’t keep a secret, such as browser and mobile apps.
// auth.mjs: the auth server's side. Short-lived JWT access tokens; opaque, rotating refresh tokens in PostgreSQL.
import { createHash, randomBytes } from "node:crypto";
import { SignJWT } from "jose";
export const ACCESS_TTL = 10 * 60; // seconds: how long a stolen access token stays useful
const IDLE = "7 days"; // a session unused for a week ends
const ABSOLUTE = "30 days"; // and every session ends after a month
const GRACE = "10 seconds"; // a second use this soon after the first is a race, not a theft
const sha256 = (token) => createHash("sha256").update(token).digest();
const newRefreshToken = () => randomBytes(32).toString("base64url"); // 256 random bits
export function createAuth({ db, privateKey, issuer, audience }) {
const accessToken = (userId, familyId) =>
new SignJWT({ sid: familyId })
.setProtectedHeader({ alg: "ES256" })
.setSubject(String(userId))
.setIssuer(issuer)
.setAudience(audience)
.setIssuedAt()
.setExpirationTime(`${ACCESS_TTL}s`)
.sign(privateKey);
// Called once the user has proved who they are (password, passkey, SSO...).
async function login(userId) {
const token = newRefreshToken();
const { rows } = await db.query(
`WITH f AS (INSERT INTO refresh_families (user_id, expires_at) VALUES ($1, now() + $2::interval) RETURNING id)
INSERT INTO refresh_tokens (hash, family_id, idle_expires_at)
SELECT $3, id, now() + $4::interval FROM f RETURNING family_id`,
[userId, ABSOLUTE, sha256(token), IDLE],
);
return { accessToken: await accessToken(userId, rows[0].family_id), refreshToken: token };
}
// Exchange a refresh token for a new access token and a new refresh token, in one SQL statement:
// only one request can mark the old token used, and its successor exists only if that worked.
async function refresh(token) {
const next = newRefreshToken();
const { rows } = await db.query(
`WITH claimed AS (
UPDATE refresh_tokens t SET used_at = now()
FROM refresh_families f
WHERE t.hash = $1 AND t.family_id = f.id AND t.used_at IS NULL
AND t.idle_expires_at > now() AND f.expires_at > now() AND f.revoked_at IS NULL
RETURNING f.id AS family_id, f.user_id)
INSERT INTO refresh_tokens (hash, family_id, idle_expires_at)
SELECT $2, family_id, now() + $3::interval FROM claimed
RETURNING family_id, (SELECT user_id FROM claimed)`,
[sha256(token), sha256(next), IDLE],
);
if (rows.length === 1) {
return { accessToken: await accessToken(rows[0].user_id, rows[0].family_id), refreshToken: next };
}
// Unknown, expired, revoked or already used. A token used before (outside the grace period) has been
// copied: revoke the whole family, so the copy and everything issued from it stop working.
await db.query(
`UPDATE refresh_families SET revoked_at = now(), revoked_why = 'refresh token reused'
WHERE revoked_at IS NULL
AND id = (SELECT family_id FROM refresh_tokens WHERE hash = $1 AND used_at < now() - $2::interval)`,
[sha256(token), GRACE],
);
return null;
}
const logout = (familyId) =>
db.query("UPDATE refresh_families SET revoked_at = now(), revoked_why = 'logout' WHERE id = $1 AND revoked_at IS NULL", [familyId]);
const logoutEverywhere = (userId) =>
db.query("UPDATE refresh_families SET revoked_at = now(), revoked_why = 'logout everywhere' WHERE user_id = $1 AND revoked_at IS NULL", [userId]);
return { login, refresh, logout, logoutEverywhere };
}Our tests checked each path:
- A refresh returned a new pair, and the old refresh token was refused afterwards.
- An attacker refreshed first; when the real user’s copy of the same token arrived a minute later, the family was revoked with the reason “refresh token reused”, and the attacker’s new refresh token stopped working too.
- Sessions past their idle or absolute limit couldn’t be refreshed.
- The database held only 32-byte hashes. The refresh tokens themselves appeared nowhere in it.
The refresh race#
Rotation creates a problem of its own. A user with two browser tabs, or an app firing ten requests at once, can easily send the same refresh token twice within a few milliseconds. With strict reuse detection, the second request looks like theft and logs the user out for no reason.
The code above handles this in two ways:
- The claim is atomic. The
UPDATE … WHERE used_at IS NULLand theINSERTof the successor are one SQL statement. When two requests arrive together, PostgreSQL makes the second wait for the first’s row lock, then re-checks the condition, findsused_atset, and updates nothing. Exactly one request gets a new token, and a successor can never exist without its predecessor being marked used. - A grace period. A spent token presented again within 10 seconds is refused, but not treated as theft. A copied token used minutes or days later still is.
Our test fired 20 refreshes with the same token at once: exactly one succeeded, 19 were refused, the family stayed active, and the winner’s new refresh token worked. The 19 losers still have a problem, though: they hold no valid token. That is the client’s job to prevent.
The client: refresh once#
// client.mjs: the caller's side. When many requests find the access token expired at once, they share one
// refresh instead of each spending the same refresh token.
export function createClient({ refresh, request }) {
let tokens;
let refreshing = null; // the refresh in progress, if any
function refreshOnce(staleAccessToken) {
if (tokens.accessToken !== staleAccessToken) return Promise.resolve(); // someone already refreshed
refreshing ??= refresh(tokens.refreshToken)
.then((next) => {
if (!next) throw new Error("session ended: sign in again");
tokens = next;
})
.finally(() => (refreshing = null));
return refreshing;
}
async function call(path) {
const used = tokens.accessToken;
let res = await request(path, `Bearer ${used}`);
if (res.status === 401) {
await refreshOnce(used);
res = await request(path, `Bearer ${tokens.accessToken}`);
}
return res;
}
return { signIn: (t) => (tokens = t), call };
}The client keeps one refresh in progress at a time and lets every request that hits a 401 wait for it. It also remembers which access token each request used, so a request that fails just after someone else refreshed simply retries with the new token instead of refreshing again. In our test, 20 API calls found the access token expired at the same moment: the client made one refresh call, and all 20 retries succeeded. Across browser tabs, the same idea needs a shared lock, such as the Web Locks API, or a backend that refreshes for all tabs (see below).
The resource server#
// api.mjs: a resource server. It checks access tokens with the public key alone: no database, no call to the
// auth server, which is the whole point of making them short-lived JWTs.
import { jwtVerify } from "jose";
export function createApi({ publicKey, issuer, audience }) {
return async function handle(path, authorization) {
const token = authorization?.replace(/^Bearer /, "");
try {
const { payload } = await jwtVerify(token ?? "", publicKey, {
issuer,
audience,
algorithms: ["ES256"],
clockTolerance: 30, // seconds of clock difference between servers
});
return { status: 200, body: { path, user: payload.sub } };
} catch {
return { status: 401 }; // expired or invalid: the client should refresh and retry once
}
};
}The API never sees a refresh token and never calls the auth server. It pins the algorithm, issuer, and audience, and allows a 30-second clock difference between machines. Any failure is a plain 401, which the client answers with one refresh and one retry.
Where refresh tokens live#
A refresh token is a long-lived credential, so where it is stored matters more than any other detail:
- Browser apps: not in JavaScript. Anything in
localStorageor a JavaScript variable can be read by an XSS attack. Put the refresh token in a cookie markedHttpOnly(scripts can’t read it),Secure(HTTPS only),SameSite=Strict(not sent with requests from other sites), and scoped withPathto the refresh endpoint, so it isn’t sent with every request. - Better still, a backend-for-frontend (BFF). A small server next to the web app holds both tokens; the browser only has an
HttpOnlysession cookie for the BFF. The tokens never reach the browser at all, and the BFF refreshes once for every tab. This is the pattern the IETF’s guidance for browser-based apps recommends most strongly. - Encrypted state layers. If the session lives in a cookie rather than a server-side store, encrypt it, for example as a JWE with a key only the server has (see JWS vs. JWE). Rotation and reuse detection still need the database row, so the encrypted cookie carries the refresh token; it doesn’t replace the table.
- Mobile apps: the platform’s secure storage, the iOS Keychain or the Android Keystore, never plain preferences or files.
- Services calling services usually don’t need refresh tokens: the OAuth client-credentials grant lets a service request a new access token with its own credentials whenever it needs one.
Logout and revocation#
Logging out revokes the family, so that device’s refresh token stops working; in our test, the user’s other device stayed signed in. “Log out everywhere”, after a password change for example, revokes all of the user’s families. In both cases, access tokens already issued keep working until they expire, which is why their lifetime is short. If even ten minutes is too long for some events, such as a disabled account or a detected compromise, resource servers can additionally check a small, short-lived denylist of revoked session IDs: the sid claim in the access token exists for exactly that.
FAQ#
Why not long-lived access tokens with a denylist?
Because then every API must check the denylist on every request, and the token is no longer stateless: you pay for a lookup on every call instead of one refresh every few minutes. A denylist works best as a backstop for rare events, with each entry kept only as long as the access token lifetime.
Should refresh tokens be JWTs?
There is little benefit. The auth server must check the database on every refresh anyway, for revocation and reuse, so the self-contained claims add size without saving a lookup. An opaque random string can’t be decoded, can’t be accepted without the lookup by mistake, and is easy to hash.
What about sliding sessions?
The idle limit is a sliding session: each refresh issues a token with a fresh 7-day idle limit. The absolute limit is what stops it sliding forever. Without one, a stolen session that keeps refreshing never ends.
Can a refresh token be bound to the device?
Yes. DPoP (RFC 9449) binds tokens to a key pair the client holds, so a copied token is useless without the private key. It adds complexity and is most valuable for public clients that can’t use a BFF. Rotation and DPoP can be combined.
How do I check what an access token contains?
Paste it into our JWT decoder: it shows the claims, including when the token was issued and when it expires, and can verify the signature with a public key or JWKS.
Get the code
- jwt-dpop-sample on GitHub: short-lived access tokens and rotating refresh tokens in an ASP.NET Core API and an Angular client, with the refresh token encrypted and bound to a key in the browser.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode an access token to check its exp and iat claims, and verify its signature with a public key or JWKS.
- JWE Decoder, Encoder & Editor: inspect an encrypted session cookie or encrypted token and decrypt it with a shared key.