Access Token Best Practices: Storage, Expiry and Rotation
How to handle access tokens safely: where to store them in the browser, how long they should live, refresh token rotation, validation, revocation and logging.
· 9 min read
An access token is a bearer credential: whoever holds it can use it. Handling tokens well therefore comes down to two goals.
- Make the token hard to steal.
- Make a stolen token nearly worthless.
Every practice below serves one of those two goals. If you are new to tokens, read access tokens and refresh tokens explained first.
1. Keep access tokens short-lived
Time is the simplest defence. A token that expires in ten minutes gives a thief ten minutes.
| Token | Sensible lifetime |
|---|---|
| Access token | 5 to 15 minutes |
| Refresh token | Hours to a few weeks, with rotation |
| Session after no activity | Shorter for sensitive apps such as banking |
These are starting points, not rules: the more damage a token could do, the shorter it should live. Use a refresh token to keep the user signed in. Do not solve the convenience problem by issuing an access token that lasts a month.
2. Choose where the browser keeps the token carefully
This is the decision people argue about most, so it is worth being precise about what each option protects against.
| Where | Can injected JavaScript read it? | Sent automatically? | Main risk |
|---|---|---|---|
localStorage |
Yes | No | Any XSS bug steals the token outright |
sessionStorage |
Yes | No | The same, limited to one tab |
| A JavaScript variable (memory) | Harder, but possible | No | Lost on page reload |
HttpOnly cookie |
No | Yes | CSRF, which has well-known defences |
Avoid localStorage for tokens. It is readable by every script on the page, including any third-party script you load and any script an attacker manages to inject. One XSS bug, anywhere on the site, and the token can be copied to the attacker's server and used from there until it expires.
Prefer an HttpOnly cookie, set by your server. JavaScript cannot read it, so an injected script cannot carry it away.
It is important not to overstate this. If an attacker can run script in your page, they can still make requests from that page, and the browser will attach the cookie. HttpOnly does not make XSS harmless. What it does is stop the token leaving the browser, which keeps the attack tied to the victim's open tab and ends it when they close the page. That is a real improvement, and it is why fixing XSS and storing tokens well are both necessary.
The strongest pattern: keep tokens on the server
For a browser app, the most robust design is a small backend that sits between the browser and the API, often called a backend for frontend (BFF):
- The backend handles the sign-in and receives the tokens.
- It keeps them on the server, and gives the browser only a session cookie.
- The browser calls the backend. The backend attaches the access token and forwards the request to the API.
Browser ── session cookie ──▶ Your backend ── access token ──▶ API
(HttpOnly, Secure) (tokens stay here)The tokens never reach the browser at all, so there is nothing for a script to steal. This is the approach current IETF guidance for browser-based apps recommends where it is practical.
If the token must live in the browser
Some apps have no backend. In that case:
- Keep the access token in memory, not in storage.
- Keep its lifetime short.
- Use refresh token rotation (see point 5).
- Treat XSS prevention as critical, with a strict content security policy.
3. Set every cookie attribute
If a token or session ID is in a cookie, set all of these:
res.cookie("__Host-session", value, {
httpOnly: true, // not readable from JavaScript
secure: true, // HTTPS only
sameSite: "lax", // not sent on most cross-site requests
path: "/",
maxAge: 1000 * 60 * 60 * 8,
});The __Host- prefix is a browser-enforced promise: the cookie must be Secure, must have Path=/, and cannot be set for a parent domain. It stops another subdomain from overwriting your cookie.
Because cookies are sent automatically, also add CSRF protection for any request that changes data. XSS and CSRF explained shows how.
4. Send tokens only in the Authorization header, over HTTPS
Authorization: Bearer <token>Never put a token in a URL. A query string such as ?access_token=... ends up in:
- the browser's history,
- server and proxy access logs,
- the
Refererheader sent to other sites, - screenshots and links people paste into chat.
And never send a token over plain HTTP, where anyone on the network path can read it.
5. Rotate refresh tokens and detect reuse
A refresh token lives a long time, so it needs its own protection. Rotation means every time a refresh token is used, the server issues a new one and retires the old one.
Rotation makes theft detectable:
- The attacker steals refresh token A.
- The real app uses A and receives B. Token A is now retired.
- The attacker tries to use A.
- The server sees a retired token being used. That can only mean it was copied.
- The server revokes the whole chain of tokens for that sign-in, and the user must sign in again.
async function refresh(presentedToken) {
const record = await db.refreshTokens.find(hash(presentedToken));
if (!record) throw new Unauthorized();
if (record.usedAt) {
// A retired token was presented: assume theft.
await db.refreshTokens.revokeFamily(record.familyId);
throw new Unauthorized();
}
await db.refreshTokens.markUsed(record.id);
return issueTokens(record.userId, record.familyId);
}Two details in that example matter:
- The server stores a hash of the refresh token, not the token itself, so a database leak does not hand out working tokens.
- Tokens issued from one sign-in share a family ID, so they can all be revoked together.
6. Give each token the least power that works
A stolen token can do whatever it was issued to do, so issue as little as possible.
- Scopes. A token for reading messages should not be able to delete the account. Ask for narrow scopes such as
messages:read. - Audience. Issue each token for one API, and have that API reject tokens meant for another. Otherwise a token leaked from a minor service works against an important one.
- No wildcard tokens for convenience during development that then reach production.
7. Validate every token, on every request
The API must not assume a token is good because it looks right. For each request, verify:
- the signature, with an algorithm fixed in the server's configuration,
- the expiry (
exp), - the issuer (
iss), - the audience (
aud), - the scope needed for this action.
Use a maintained library and pass it the expected values. Decoding a JWT and reading its fields is not validation: an attacker can write any payload they like, and only the signature check catches it.
8. Have a way to revoke
Signed tokens such as JWTs are valid until they expire, which is awkward when you need to cut off access now. Plan for it:
- Keep access tokens short-lived, so "wait for it to expire" is a matter of minutes.
- Revoke the refresh token on logout, password change and account suspension. Without it, no new access tokens can be issued.
- For high-risk actions, keep a small deny list of revoked token IDs, or check the token with the login server.
- Offer users a "sign out of all devices" button. It is also your emergency tool after a breach.
9. Keep tokens out of logs and error reports
Tokens leak through tooling more often than through attacks.
- Redact the
AuthorizationandCookieheaders in request logs. - Check what your error-tracking and analytics tools capture. Many record full request headers by default.
- Do not paste real tokens into tickets, chat or public code examples.
- If a token does appear somewhere it should not, treat it as stolen and revoke it.
10. Use the right sign-in flow
For OAuth and OpenID Connect, the recommended flow for browser and mobile apps is the authorization code flow with PKCE.
Two older flows should not be used in new systems:
- The implicit flow, which returned the access token in the URL.
- The password grant, where the app collected the user's password itself and sent it to the login server.
PKCE (said "pixy") protects the sign-in: even if an attacker intercepts the authorization code, they cannot exchange it for tokens without a secret that only the real app holds. Use a maintained OAuth library, which implements this for you.
11. Keep secrets on the server
- A client secret or signing key in front-end code is public. Browser and mobile apps cannot keep secrets.
- Load signing keys from a secrets manager or environment variables, never from the repository.
- Prefer asymmetric signing (for example RS256 or ES256): the login server keeps the private key, and APIs only need the public key, so a compromised API cannot forge tokens.
- Rotate signing keys on a schedule, and publish the public keys where your APIs can fetch them.
12. Bind tokens to the client where the risk justifies it
Ordinary bearer tokens work for anyone who holds them. Sender-constrained tokens do not: the token is tied to a key that only the legitimate client has, so a copied token is useless alone. The two standard mechanisms are DPoP and mutual TLS.
This adds complexity, so it is mostly used where the stakes are high, such as payments and health data. It is worth knowing it exists.
Checklist
| Practice | Goal |
|---|---|
| Access tokens live for minutes | Worthless if stolen |
Tokens kept on the server, or in an HttpOnly cookie |
Hard to steal |
Never in localStorage |
Hard to steal |
Cookies: HttpOnly, Secure, SameSite |
Hard to steal |
Sent in the Authorization header, never in a URL |
Hard to steal |
| HTTPS everywhere | Hard to steal |
| Refresh tokens rotate, with reuse detection | Worthless if stolen |
| Narrow scopes and one audience per token | Worthless if stolen |
| Signature, expiry, issuer, audience checked every time | Forgery fails |
| Refresh tokens revoked on logout and password change | Worthless if stolen |
| Tokens redacted from logs | Hard to steal |
| Authorization code flow with PKCE | Hard to steal |
No single item makes tokens safe. Together they mean an attacker has to defeat several independent defences, and gains very little if they do.
Further reading
- RFC 9700: Best Current Practice for OAuth 2.0 Security: the current security recommendations for OAuth.
- OAuth 2.0 for Browser-Based Applications: IETF guidance on the backend-for-frontend and other patterns.
- RFC 7636: Proof Key for Code Exchange: the PKCE specification.
- RFC 9449: OAuth 2.0 Demonstrating Proof of Possession: the DPoP specification.
- OWASP Session Management Cheat Sheet: cookie and session guidance.