Refresh Tokens Explained
Why JWT logins use two tokens, how long each should last, how rotation catches a stolen refresh token, and where web and mobile apps should keep them.

JWT Explained ended on a problem: once a server hands out a JWT, it can't take it back. A stolen token keeps working until it expires, even if the user logs out or changes their password.
The usual fix is to use two tokens instead of one. This post covers why that works, how long each token should last, how rotation catches a thief, and where web and mobile apps should keep them.
Two tokens, two jobs
| | Access token | Refresh token |
|---|---|---|
| What it is | A JWT | A long random string |
| Lasts | Minutes (5–15 is common) | Days or weeks |
| Sent | With every API request | Only to /refresh |
| Checked by | Its signature, no database | A lookup in the database |
| Can be cancelled | No, it works until exp | Yes, delete its row |
The two lifetimes are different on purpose:
- The access token is short-lived because it can't be cancelled. If one is stolen, it stops working within minutes.
- The refresh token is long-lived so the user stays logged in. When the access token expires, the app quietly swaps the refresh token for a new one. The user never sees a login screen.
- The refresh token lives in the database, so it can be cancelled. Every refresh is a chance to ask "has this user logged out, or been banned?" Logging out deletes the refresh token, so the next refresh fails, and the user is fully logged out within one access-token lifetime.
A common setup is a 15-minute access token and a 7-day refresh token.
A refresh token is like a session id
A refresh token works just like a session id, so it gets the same care as one
in Sessions Explained: made with
crypto.randomBytes, and stored only as a SHA-256 hash, so a leaked database
doesn't contain working tokens.
Each refresh token is one row:
type RefreshToken = { tokenHash: string; // a SHA-256 hash of the token in the cookie userId: string; // who it belongs to expiresAt: Date; // when it stops working usedAt: Date | null; // set once it has been swapped for a new one};Here's the code. signToken is the function from
JWT Explained that makes the access token.
import { createHash, randomBytes } from "node:crypto";import { parseCookie } from "cookie";
const REFRESH_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days, in milliseconds
function hashToken(token: string) { return createHash("sha256").update(token).digest("hex");}
// Call this at login too, next to signToken.async function issueRefreshToken(res: Response, userId: string) { const refreshToken = randomBytes(32).toString("base64url"); await db.refreshToken.create({ data: { tokenHash: hashToken(refreshToken), userId, expiresAt: new Date(Date.now() + REFRESH_TTL), }, });
res.cookie("refreshToken", refreshToken, { httpOnly: true, secure: true, sameSite: "strict", path: "/refresh", // only sent to the refresh route maxAge: REFRESH_TTL, });}
app.post("/refresh", async (req, res) => { const refreshToken = parseCookie(req.headers.cookie ?? "").refreshToken; if (!refreshToken) return res.sendStatus(401);
const tokenHash = hashToken(refreshToken);
// Mark the token as used. This only matches a token that is unused and // unexpired, so two requests with the same token can't both get through. const { count } = await db.refreshToken.updateMany({ where: { tokenHash, usedAt: null, expiresAt: { gt: new Date() } }, data: { usedAt: new Date() }, });
const stored = await db.refreshToken.findUnique({ where: { tokenHash }, include: { user: true }, });
if (count === 0) { // A token that was already used has come back. Within a few seconds of its // use, that's most likely a second tab racing the first. Later than that, // two people have a copy, and we can't tell which one is the thief, so // log the user out everywhere. const GRACE_MS = 10_000; if (stored?.usedAt && Date.now() - stored.usedAt.getTime() > GRACE_MS) { await db.refreshToken.deleteMany({ where: { userId: stored.userId } }); } return res.sendStatus(401); }
await issueRefreshToken(res, stored!.userId); res.json({ accessToken: await signToken(stored!.user) });});Rotation: every refresh token works once
Every refresh swaps the old refresh token for a new one. This is called rotation:
POST /refresh (token A) → new access token + token B, A marked usedPOST /refresh (token B) → new access token + token C, B marked usedPOST /refresh (token A) → A was already used: log alice out everywhereThe used tokens stay in the table, marked with usedAt, and that's what
catches a thief. Say someone copies alice's refresh token. Sooner or later,
both alice and the thief try to use it. Whoever goes first gets a new token;
whoever goes second shows a token that's already been used. The server can't
tell which of them is the real alice, so it deletes all of her refresh tokens,
including the new one. The thief is locked out, and alice just has to log in
again.
Without rotation, the same refresh token would be reused until it expired. A stolen copy would work for its whole lifetime, and nothing would ever show that it had been stolen.
The grace period
The 10-second grace period is for a harmless reuse: two tabs refreshing at
the same moment with the same cookie. One wins; the other gets a 401, but by
then the browser already holds the winner's new cookie, so trying once more
works. Without the grace period, opening the app in two tabs could log
someone out. The cost is that a thief who uses the token within those 10
seconds isn't caught, which is a narrow window.
How long a user stays logged in
Each new refresh token gets a fresh 7 days, so the 7 days count from the last refresh, not from login. That gives you an inactivity limit for free: someone who doesn't open the app for a week is logged out, but someone who uses it every day stays logged in.
If you also want everyone to log in again eventually, add a second, fixed limit: store the time of the original login on each row, carry it over on every rotation, and refuse to refresh once it's more than, say, 30 days old.
Used rows can be deleted once their expiresAt has passed, by the same kind
of cleanup job as for sessions.
Where a web app keeps the tokens
localStorage: easy to use, but any JavaScript on the page can read it. One cross-site scripting (XSS) bug, or one bad npm package, and the token is gone.- An
httpOnlycookie: JavaScript can't read it at all, and the browser sends it automatically. (An XSS bug can still send requests with it from the page, but it can't copy the token and use it elsewhere.) AddSecure(HTTPS only) andSameSiteto protect against other sites making requests with it. See SameSite Cookies Explained.issueRefreshTokenabove sets all three, pluspath: "/refresh"so the cookie goes nowhere else.
A common setup is to keep the refresh token in an httpOnly cookie and the
short-lived access token in memory (a variable, not storage), so a page reload
just calls /refresh again.
Where a mobile app keeps the tokens
A mobile app has no httpOnly cookies to hide behind. Instead, it uses the
phone's own secure storage, which encrypts secrets with keys held in hardware
and keeps every app's secrets apart:
| Platform | Use | Don't use |
|---|---|---|
| iOS | The Keychain | UserDefaults, plain files |
| Android | A key in the Android Keystore that encrypts the token | Plain SharedPreferences or DataStore |
| React Native | react-native-keychain or expo-secure-store | AsyncStorage |
| Flutter | flutter_secure_storage | shared_preferences |
The cross-platform libraries use the Keychain and the Keystore underneath. The split is the same as on the web: the refresh token goes in secure storage so it survives a restart, and the access token stays in memory.
A few settings are worth turning on:
- Keep it on this device. On iOS, store the token with an accessibility
setting that ends in
ThisDeviceOnly, such askSecAttrAccessibleAfterFirstUnlockThisDeviceOnly. That keeps it out of iCloud and backups, so it can't be restored onto another phone. On Android, leave the token's storage out of Auto Backup. - Ask for Face ID or a fingerprint before reading the token, for apps where that's worth the extra step, like banking.
The threats are different on a phone. In a browser, the worry is JavaScript on the page stealing the token. On a phone, it's other apps, a lost or rooted device, and backups, which is what the OS's secure storage is built for.
Serving web and mobile from one backend
Since mobile apps don't use cookies for this, the same backend hands out the refresh token in two ways:
Web: POST /refresh Cookie: refreshToken=... ← { accessToken } Set-Cookie: refreshToken=<new>; HttpOnly
Mobile: POST /mobile/refresh { "refreshToken": "..." } ← { accessToken, refreshToken: <new> }Everything else stays the same: the same table, the same rotation, the same
reuse check. Only how the token travels changes. A mobile app sends no
cookies, so it doesn't need the SameSite and CSRF protections the web route
does.
Keep the two apart with something you control, like a separate route or a
registered client id. Don't decide by the User-Agent header, which anyone
can set.
The short version
- Use two tokens: a JWT access token that lasts minutes, and a random refresh token that lasts days and lives in the database.
- Logging out deletes the refresh token, so the user is fully logged out within one access-token lifetime.
- Store refresh tokens hashed. Rotate them on every use, and log the user out everywhere if a used one comes back after a short grace period.
- On the web, keep the refresh token in an
httpOnly,Secure,SameSitecookie and the access token in memory. - On mobile, keep the refresh token in the Keychain or Keystore, never in plain app storage.
- If one backend serves both, only the mobile route may return the refresh token in the response body.