Track 07 · Lesson 9 of 18Identity and login

Track 07 · Identity and login

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
Fresh: send as is. More than 60 seconds left by the browser’s clock. The interceptor attaches Authorization: Bearer and sends. No refresh.

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

Why should the HTTP client used for login and refresh have no refresh interceptor?