Siti logs in at 07:00. Her access token (the token sent with every request) is valid for 15 minutes, so at 07:15 it expires, while Siti is still reading her report card. The short life is on purpose, so a leaked token soon becomes useless. But should Siti log in again every 15 minutes?
The refresh flow solves it with two tokens. The access token is short-lived and goes with every request. The refresh token is long-lived and used for one thing only: getting a new access token. Picture an office building. In the lobby you get a visitor badge that is valid for 15 minutes, and that is the badge you tap on every door. When its time has passed, you go to the front desk, show your monthly pass (which you never tap on any door), and get a new visitor badge. The visitor badge is the access token, and each door is one request. The monthly pass is the refresh token, and the front desk is the POST /auth/refresh endpoint (an endpoint is a route that is called from outside the server).
Two tokens, two lifetimes
In School Portal, this track's example app, Siti's login is answered with two tokens:
| Access token | Refresh token | |
|---|---|---|
| Lifetime | 15 minutes | 30 days |
| Form | a signed token (JWT or PASETO) | a random string with no content (opaque) |
| The client keeps it in | a JavaScript variable (memory) | an HttpOnly cookie |
| Sent to | every API request, in the Authorization header |
only POST /auth/refresh |
| If it leaks | valid for 15 minutes at most | can be revoked, since the server records it in the database |
This is the server's answer to the login:
HTTP/1.1 200 OK
Set-Cookie: refresh_token=R1; Max-Age=2592000; Path=/auth/refresh; Secure; HttpOnly; SameSite=Strict
Content-Type: application/json
{"access_token": "A1", "token_type": "Bearer", "expires_in": 900}
expires_in: 900: the access token is valid for 900 seconds, which is 15 minutes. The tokens in this example are written short (A1,R1) so they are easy to follow; real ones are long strings.HttpOnly: JavaScript on the page cannot read this cookie (document.cookiedoes not show it), but the browser still sends it automatically.Path=/auth/refresh: the browser includes this cookie only with/auth/refresh, not with any other request.SecureandSameSite=Strict: the cookie is sent only over HTTPS, and never with a request that comes from another site.Max-Age=2592000: 30 days in seconds.
The access token is deliberately not kept in localStorage, because every script on the page can read it. Because it lives only in memory, the access token is gone when the page reloads. That is fine: the refresh token cookie is still there, so as soon as the app opens again, the client calls /auth/refresh once.
Why not one long-lived token? If the access token leaks, the damage is limited: 15 minutes later that token is no longer valid. The long-lived refresh token is rarely sent (only to one endpoint), and the server can revoke it.
The flow, on a virtual clock
Siti logs in on Friday, 9 October 2026, at 07:00. This is what happens, exactly as in the Lab:
| Time | Request | Server's answer | What the client does |
|---|---|---|---|
| 07:00 | POST /auth/login |
200, access token A1 (expires 07:15), cookie R1 (expires 8 Nov 07:00) |
keeps A1 in memory |
| 07:10 | GET /students/1/grades with A1 |
200 |
shows the report |
| 07:20 | GET /students/1/grades with A1 |
401, token expired |
no login page yet, refresh |
| 07:20 | POST /auth/refresh with cookie R1 |
200, A2 (expires 07:35), cookie R2 |
keeps A2 |
| 07:20 | GET /students/1/grades with A2 |
200 |
the report shows, Siti notices nothing |
The 401 answer at 07:20 comes with a header that explains why:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="The access token expired"
So when the client gets a 401, its first move is to try a refresh, then repeat the request. Only if the refresh fails too (the refresh token expired or was revoked) is Siti sent to the login page.
The client code: fetchWithAuth
Every API request goes through one function, fetchWithAuth. The function attaches the access token to the header. If the answer is a 401, the function refreshes, then retries the request once.
let accessToken = null; // in memory, not localStorage
let refreshing = null; // the refresh promise currently running, shared
async function refreshAccessToken() {
const res = await fetch("/auth/refresh", { method: "POST", credentials: "include" });
if (!res.ok) throw new Error("refresh failed");
accessToken = (await res.json()).access_token;
}
function refreshOnce() {
if (!refreshing) {
refreshing = refreshAccessToken().finally(() => {
refreshing = null;
});
}
return refreshing;
}
async function fetchWithAuth(url, options = {}) {
const send = () =>
fetch(url, { ...options, headers: { ...options.headers, Authorization: `Bearer ${accessToken}` } });
const res = await send();
if (res.status !== 401) return res;
try {
await refreshOnce();
} catch {
window.location.assign("/login"); // the refresh token expired or was revoked
return res;
}
return send(); // retried once only
}
credentials: "include"asks the browser to include cookies, also when the API is on another origin (a different domain or port).refreshingholds the refresh promise that is running.refreshOnce()creates a refresh promise only when none is running. Other requests that also got a401wait for the same promise..finally(...)clearsrefreshingonce the refresh is finished, success or failure, so the client can refresh again the next time the access token expires.return send()happens once. If the retry still gets a401, the function ends instead of looping./auth/refreshis called with plainfetch, notfetchWithAuth. ThroughfetchWithAuth, a401from the refresh would start another refresh, forever.
Three requests, one refresh
At 07:20, Siti's dashboard sends three requests at once: the report (/students/1/grades), the timetable (/students/1/schedule) and the announcements (/announcements). All three carry A1, and all three get a 401. How many times should the client call /auth/refresh: once, or three times?
If every request refreshes on its own, all three carry the same cookie, R1. They are all sent before the first answer arrives:
| Refresh | Cookie | Answer |
|---|---|---|
| 1st | R1 |
200, gets A2 and R2. R1 is marked as used |
| 2nd | R1 |
401, R1 was already used |
| 3rd | R1 |
401, R1 was already used |
The 2nd refresh fails, so fetchWithAuth sends Siti to the login page, although her login is still valid. With refreshOnce(), the 2nd and 3rd requests wait for the same promise: 1 refresh, 3 requests retried, 3 times 200. So once is enough.
Refresh token rotation
Why is R1 refused at the 2nd refresh? Because the School Portal server uses refresh token rotation: every time a refresh token is used, the server issues a new refresh token and marks the old one as no longer valid. So one refresh token works only once. If an old token appears again, something is wrong (that token may have been stolen), and the server can revoke all of that user's sessions. How to detect it is built in the Refresh Token Rotation lesson.
📌 The refresh endpoint in Laravel
Route::post('/auth/refresh', function (Request $request) {
$token = RefreshToken::where('token_hash', hash('sha256', (string) $request->cookie('refresh_token')))
->whereNull('used_at')
->where('expires_at', '>', now())
->first();
abort_if($token === null, 401, 'Unauthenticated.');
// rotation: claim the old token atomically, so only one request can exchange it
$claimed = RefreshToken::whereKey($token->id)->whereNull('used_at')->update(['used_at' => now()]);
abort_if($claimed !== 1, 401, 'Unauthenticated.');
$plain = Str::random(64);
$token->user->refreshTokens()->create([
'token_hash' => hash('sha256', $plain),
'expires_at' => now()->addDays(30),
]);
return response()
->json(['access_token' => AccessToken::for($token->user), 'token_type' => 'Bearer', 'expires_in' => 900])
->cookie('refresh_token', $plain, 60 * 24 * 30, '/auth/refresh', null, true, true, false, 'strict');
});
- The database keeps only the hash of the refresh token. If the database leaks, the tokens don't leak with it.
whereNull('used_at')andexpires_atrefuse a token that was already used or has expired.- Two requests that carry the same token at the same moment can both pass
first()(the search for the matching token row). Soused_atis set with anupdate()that also checkswhereNull('used_at'). The database changes that row only once, so only one request gets1(the number of rowsupdate()changed). The other gets0and is refused with401, instead of getting a new token too. AccessToken::for(...)is a helper of this app that makes a 15-minute access token, for example PASETO as in the previous lesson.- The
->cookie(...)arguments, in order: name, value, lifetime in minutes (30 days), path, domain,Secure,HttpOnly, raw,SameSite.
⚠️ Refreshes that leak, loop, or go to the wrong place
- A refresh token in
localStorage. Every script on the page can read it, and it lives 30 days. Put it in anHttpOnlycookie. - Every request refreshes on its own. With rotation, the second and later refreshes are refused, and the user lands on the login page. Use one shared refresh promise.
- Retrying without a limit. Retry the request once only, and never call
/auth/refreshthroughfetchWithAuth. - Refreshing on a
403. A403means the permission is missing, not that the token has expired. A refresh won't help, so show "access denied".
TL;DR: A short-lived access token (15 minutes) is kept in memory and goes with every request. A long-lived refresh token (30 days, opaque: a random string with nothing inside) is kept in an HttpOnly cookie and sent only to POST /auth/refresh to ask for a new access token. If the access token leaks, the damage is limited. A request gets a 401: refresh once, then retry the request once. The refresh gets a 401 too: send the user to the login page. When many requests get a 401 together, one refresh is still enough, through one shared promise. Rotation issues a new refresh token on every use, so an old one cannot be used again.
⚡ Two tokens, two lifetimes
Meaning: The access token is short-lived (15 minutes), kept in memory, and goes with every request. The refresh token is long-lived (30 days), kept in an HttpOnly cookie, and sent only to POST /auth/refresh to ask for a new access token. If the access token leaks, the damage is limited: 15 minutes later that token is no longer valid.
⚡ Got a 401: refresh, then retry once
Meaning: As soon as a request gets a 401 (the server doesn't accept its token), the client tries a refresh first, then repeats the request once only. Only if the refresh gets a 401 too (the refresh token expired or was revoked) is the user sent to the login page. A 403 means the permission is missing, so a refresh won't help.
⚡ One refresh for many requests
Write:
function refreshOnce() {
if (!refreshing) {
refreshing = refreshAccessToken().finally(() => {
refreshing = null;
});
}
return refreshing;
}
Guess first: at 07:20 Siti's dashboard sends three requests at once, and all three get a 401. The server uses rotation: each refresh token works only once. How many times should the client call /auth/refresh?
Once. If every request refreshes on its own, all three carry the same refresh token cookie, R1. The first refresh works, the second and third are refused because R1 was already used, and Siti lands on the login page.
Meaning: refreshing holds the refresh promise that is running, and refreshOnce() starts a new refresh only when there is none. So the second and third requests wait for the same promise. .finally(...) clears refreshing so the client can refresh again the next time the access token expires.