Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Tokens, JWT and OAuth

Access Tokens and Refresh Tokens

Learn why APIs pair short-lived access tokens with refresh tokens, how refresh token rotation and reuse detection work, with a runnable Node.js API.

A short-lived access token limits the damage of theft, but asking users to log in every ten minutes is unusable. The answer is a second token. The access token is short-lived and goes with every API call. The refresh token is long-lived, is used only to get a new access token, and is sent only to the auth endpoint.

This split keeps most requests stateless and cheap (verify a signature), while the rare refresh request hits a database where you can revoke, rotate and audit. In this lesson you will build both halves: a token service that rotates refresh tokens and detects theft, and a small HTTP API that uses it.

Two tokens, two jobs

Access token Minutes. Sent on every call.
Refresh token Days. Sent only to /token.
Stored server side Refresh tokens can be revoked.

Stateless where it is cheap, stateful where it is safe.

1 / 2

What a refresh token looks like

A refresh token does not have to be a JWT. The simplest and safest form is an opaque random string that means nothing by itself:

JavaScript
import { randomBytes, createHash } from 'node:crypto';

const refreshToken = randomBytes(32).toString('base64url'); // give this to the client
const stored = createHash('sha256').update(refreshToken).digest('hex'); // save only this

Store a hash of the token, never the token. If your database leaks, the attacker gets hashes they cannot use. A fast hash such as SHA-256 is fine here, because the token already has 256 bits of randomness and cannot be guessed (unlike a password).

Each stored record holds the user, an expiry, a family ID and a used flag. The next section explains why.

Rotation and reuse detection

Rotation means every refresh gives back a new refresh token and invalidates the old one. A refresh token is therefore single-use. This gives you a way to detect theft:

  1. The legitimate client and a thief both hold refresh token R1.
  2. One of them refreshes first and receives R2. R1 is now used.
  3. The other one presents R1. It was already used, which should never happen to an honest client.
  4. The server concludes the token family is compromised and revokes every token in that family. Both parties must log in again.
Node.js Rotation with reuse detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A common refinement allows a short grace period (a few seconds) for the old token, because a flaky network can make an honest client retry the same refresh request. Without it, a retry would wrongly look like theft.

An API that uses both tokens

This server has four routes: POST /login, POST /refresh, GET /me (needs a valid access token) and POST /logout. Access tokens are HS256 JWTs valid for 60 seconds (a short life, so the demo can show an expiry). The program calls itself with fetch, so you can watch the whole sequence. Time is simulated with a variable so the output never depends on how fast the code runs.

Node.js Login, expire, refresh, logout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the status codes: 401 with token expired is the client's signal to call /refresh once and retry. A 401 from /refresh itself means the session is over and the user must log in again.

Client behavior

A well-behaved client:

  1. Keeps the access token in memory and the refresh token in the most protected storage available (an HttpOnly cookie for browsers, secure storage on mobile).
  2. Refreshes once when it receives a 401 (or just before expiresIn runs out), and lets parallel requests wait for that one refresh instead of firing several.
  3. Replaces both tokens with the pair it receives, because rotation invalidated the old refresh token.
  4. Sends the user to the login page if the refresh fails.

Choosing lifetimes

Token Typical lifetime If stolen
Access 5 to 15 minutes Works until it expires
Refresh (web) 7 to 30 days, often sliding Detected by rotation, family revoked
Refresh (high security) Hours, tied to a device Re-authenticate often

Add an absolute maximum session length too, so a refresh chain cannot continue forever.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which token is sent with every API request?

    The access token proves identity on each call. The refresh token goes only to the token endpoint.
  2. 2. Why store only a hash of an opaque refresh token?

    If the database leaks, an attacker sees hashes and cannot present them as tokens.
  3. 3. A refresh token that was already used is presented again. What should a rotating server do?

    An honest client holds only the newest token, so reuse of an old one means a copy exists somewhere.
  4. 4. Why might a server allow a few seconds of grace for a just-rotated refresh token?

    A client may send the same refresh twice when a response is lost. A short grace window avoids logging out honest users.
  5. 5. What should a client do when /refresh itself returns 401?

    A failed refresh means the session is over (expired, revoked or reused), so the user must authenticate again.

Summary

  • Access tokens are short-lived and stateless; refresh tokens are long-lived, opaque and stored hashed on the server.
  • Rotation makes each refresh token single-use; reuse of an old one reveals theft and revokes the whole family.
  • A 401 on an API call triggers one refresh and a retry; a failed refresh means log in again.
  • Logout deletes the refresh token on the server; the short access token expires by itself.
  • Add an absolute session limit so refresh chains end.

Next: OAuth 2.0 Flows and PKCE