Track 07 · Lesson 9 of 18Identity and login
- 01Authentication vs authorization
- 02Browser storage compared
- 03Sessions versus tokens
- 04Inside a JWT
- 05Access and refresh tokens
- 06Where to keep tokens
- 07Choosing a design
- 08The login lifecycle
- 09The token clock
- 10Dead or just unlucky? Refresh decisions
- 11Inside a secure session cookie
- 12Five tabs, one refresh
- 13“Log in with Google”: OAuth and PKCE
- 14Two-factor login
- 15Storing passwords
- 16Logging out properly
- 17Trade-offs and common mistakes
- 18Compare the designs
The token clock
Lesson 9 of 18· 6 min
Any app with short-lived access tokens needs to replace them before or after they expire. The robust approach has two layers: refresh early, and recover once if a 401 slips through anyway.
Drag time across a token
Then make the laptop’s clock slow
✓ Fresh · ◐ Last 60 s: Layer 1 window · ✕ Expired
- Real time left
- 40m 00s
- Browser believes
- 40m 00s
- Server says
- valid
Layer 1: refresh early#
Before every request, if the token has 60 seconds or less left, refresh first. Servers allow only a little clock skew (the example allows 5 seconds; libraries default to anything from 0 seconds to 5 minutes). Refreshing a minute early leaves room for skew plus request latency, so in the common case no request ever sees a 401. Look for it in a request interceptor, often named isExpired or willExpireSoon.
Layer 2: recover once#
If a 401 comes back anyway (a slow laptop clock, a token revoked mid-session), refresh once and retry the request once. Mark the retry, for example _retried = true. If it 401s again, hand the error to the caller instead of starting another refresh. Without that guard, a broken token loops forever.
The client that refreshes can’t refresh itself#
The HTTP client used for login and refresh calls must not run the refresh interceptor itself, or a failed refresh can trigger another refresh, forever. Keep auth calls on a separate client.
Check yourself