Skip to the page

Forms, routing and HTTP · mid

Functional HTTP interceptors and token refresh

An interceptor is a function that can change every request or response. A token refresh must run once, with every waiting call sharing it.

The notes

What you must know

  • A functional interceptor: HttpInterceptorFn = (req, next) => ..., registered with provideHttpClient(withInterceptors([...])).
  • Requests are immutable: use req.clone({ setHeaders }).
  • Add the token only to your own API URLs, never to third-party URLs.
  • HttpContextToken lets one request opt out, for example SKIP_AUTH on the login and refresh calls.
  • Token refresh storm: 12 calls get 401, and each starts its own refresh. A server that rotates refresh tokens sees reuse as theft and ends the session.
  • Fix: one refresh in flight, shared by every waiting call (shareReplay, or a stored Promise), then retry the calls once.
  • If the refresh fails, log out once and do not loop.

The red pen

Common traps: mistake → fix

  • Mistake: I can change req.headers directly

    Fix: requests are immutable; clone them.

  • Mistake: Each 401 should start its own refresh

    Fix: only one refresh should run.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you add an auth header to every request?
  2. How do you skip auth for one call?
  3. What goes wrong when many calls get 401 together?
  4. How do you prevent an endless refresh loop?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview