Build Angular functional HTTP interceptors: the HttpInterceptorFn chain, token refresh, retry and caching
Problem
Since Angular 15, interceptors are plain functions: HttpInterceptorFn = (req, next) => Observable<HttpEvent>, registered with provideHttpClient(withInterceptors([...])). A senior Angular interview often asks you to write the classic three (auth with token refresh, retry with backoff, and a GET cache) and to explain what order they run in. Build the pieces of HttpClient they depend on, the chain, and the three interceptors.
const http = createHttpClient({
backend,
interceptors: [cacheInterceptor({ ttl: 30_000, clock }), authInterceptor({ getToken, refreshToken }), retryInterceptor({ clock })],
});
await http.get("/api/me"); // cache miss -> auth adds the token -> retry -> backend
await http.get("/api/me"); // cache hit: auth, retry and backend never run
await http.get("/api/config", { context: new HttpContext().set(SKIP_AUTH, true) });Ref. UR-1452 · © UIRound · uiround.com/questions/build-angular-functional-http-interceptors-the-httpinterceptorfn-chain-token-refresh-retry-and-caching
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1The chain is
interceptors.. Requests travel left to right and responses come back right to left, and callingreduceRight((next, interceptor) => (req) => interceptor(req, next), sendToBackend) nexttwice really sends twice.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.