Build Angular functional HTTP interceptors: the HttpInterceptorFn chain, token refresh, retry and caching

hardAbout 70 minutesUpdated CodingProangularhttpinterceptorsauthenticationretrycachingmiddleware
Not solved

Share this question

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

Stuck? Take a hint

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.

Every question and answer7 days, one payment