Sub topic 10
Cross-Cutting Concerns with Functional Interceptors
Some HTTP behavior belongs to every request, not to one service. Attaching an auth token, logging timings, and reacting to an expired session are examples. If you copy that logic into each TodoService method, it drifts out of sync and gets forgotten. An interceptor is a function that sits between HttpClient and the network. It sees every outgoing request and every incoming response, so you write the logic once.
This chapter assumes you already know how to register HttpClient with provideHttpClient, how HttpHeaders work, and how catchError and throwError handle failures. It also assumes you are comfortable with RxJS pipe, tap, and finalize.
The Interceptor Model
A functional interceptor has the type HttpInterceptorFn:
type HttpInterceptorFn = (
req: HttpRequest<unknown>,
next: HttpHandlerFn
) => Observable<HttpEvent<unknown>>;The function receives the outgoing request and a next function. Calling next(req) passes the request to the next interceptor in the chain. After the last interceptor, it goes to the backend that performs the real network call. next returns an Observable of HTTP events, and your interceptor returns that Observable, often with operators piped onto it.
An interceptor can make four kinds of decisions:
| Decision | How it looks in code |
|---|---|
| Pass through unchanged | `return next(req);` |
| Change the request | `return next(req.clone({ ... }));` |
| Transform or observe the response | `return next(req).pipe(tap(...), catchError(...));` |
| Short-circuit without a network call | `return of(new HttpResponse({ ... }));` |
Order of execution
You register interceptors as an array, and the order of that array matters. Requests flow through the interceptors in array order. Responses flow back in reverse order, because each interceptor's operators wrap the Observable returned by the interceptors after it.
Registering Interceptors
You pass interceptors to withInterceptors inside provideHttpClient:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { routes } from './app.routes';
import { loggingInterceptor } from './logging.interceptor';
import { authInterceptor } from './auth.interceptor';
import { errorInterceptor } from './error.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(
withInterceptors([loggingInterceptor, authInterceptor, errorInterceptor])
)
]
};Interceptors apply to the HttpClient provided by that injector. If a lazy-loaded route calls provideHttpClient() again in its own providers, it gets a separate client, and the root interceptors do not run for its requests. The fix is to call provideHttpClient once at the root, or to use withRequestsMadeViaParent() on the child client so requests also pass through the parent's chain.
An Authentication Interceptor
HttpRequest objects are immutable. Their headers, params, and body cannot be changed in place, so the interceptor creates a modified copy with clone:
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
// Only attach the token to our own API, never to third-party hosts.
if (!req.url.startsWith('/api/')) {
return next(req);
}
const token = localStorage.getItem('access_token');
if (!token) {
return next(req);
}
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authReq);
};The URL check matters. If your app also calls a public weather API or a CDN, an unscoped interceptor would send your user's token to that host. Interceptors run for every request, so you have to scope them yourself.
clone accepts setHeaders and setParams for simple additions. It also accepts headers, params, url, body, and withCredentials for full replacements.
Using Dependencies with inject()
Functional interceptors run in an injection context, so you can call inject() at the top of the function. The error interceptor below uses the Router to send the user to a login page when the server returns 401:
// error.interceptor.ts
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((error: unknown) => {
if (error instanceof HttpErrorResponse && error.status === 401) {
localStorage.removeItem('access_token');
router.navigate(['/login']);
}
return throwError(() => error);
})
);
};Two details matter here:
inject(Router)is called synchronously in the function body. If you callinjectinside thecatchErrorcallback, it fails with an injection-context error, because that callback runs later, outside the injection context.- The interceptor rethrows the error. Services and components can still react to the failure, for example by showing a message. If you return
EMPTYor a fake value instead, you swallow the error, and callers never learn that the request failed.
A Logging Interceptor
Logging shows why responses are a stream of events. next(req) can emit more than one HttpEvent per request. The HttpEventType.Sent event always comes first, and progress events can follow. Filter for HttpResponse when you only care about the final result.
// logging.interceptor.ts
import { HttpErrorResponse, HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { finalize, tap } from 'rxjs';
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = performance.now();
let outcome = 'was cancelled';
return next(req).pipe(
tap({
next: event => {
if (event instanceof HttpResponse) {
outcome = `succeeded with ${event.status}`;
}
},
error: (error: unknown) => {
const status = error instanceof HttpErrorResponse ? error.status : 'unknown';
outcome = `failed with ${status}`;
}
}),
finalize(() => {
const elapsed = Math.round(performance.now() - started);
console.log(`${req.method} ${req.urlWithParams} ${outcome} in ${elapsed} ms`);
})
);
};finalize runs on success, on error, and on unsubscribe. The initial value 'was cancelled' covers the third case. If a component is destroyed, or a switchMap drops an old request, the request is torn down without a response. The log then reports a cancellation instead of a false failure.
Because loggingInterceptor comes first in the array, it sees the original request before the auth header is added. That keeps tokens out of your logs. It also measures the full time spent in the inner interceptors and on the network.
Short-Circuiting: A Simple Cache
An interceptor does not have to call next. It can return its own Observable, and the request then never reaches the network:
// cache.interceptor.ts
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of, tap } from 'rxjs';
const cache = new Map<string, HttpResponse<unknown>>();
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
const cached = cache.get(req.urlWithParams);
if (cached) {
return of(cached.clone());
}
return next(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
cache.set(req.urlWithParams, event);
}
})
);
};This version caches every GET forever and ignores who the user is. A real app needs a way to opt specific requests in or out. The chapter on HttpContext shows how to pass that kind of per-request flag to an interceptor without relying on URL patterns.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Modifying headers without `clone` | Header silently missing | `next(req.clone({ setHeaders: ... }))` |
| Forgetting `return` before `next(req)` | Interceptor returns `undefined`; requests throw | Always return the Observable |
| Calling `next(req)` twice | Duplicate network requests | Call `next` once and pipe operators onto the result |
| Calling `inject()` inside an RxJS callback | Injection-context error at runtime | Call `inject()` at the top of the function |
| Swallowing errors in `catchError` | Callers think the request succeeded | Rethrow with `throwError(() => error)` |
| Unscoped auth interceptor | Tokens sent to third-party hosts | Check `req.url` before adding credentials |
| Second `provideHttpClient` in a lazy route | Root interceptors skipped | Provide once, or use `withRequestsMadeViaParent()` |
| Mixing in class interceptors | Class interceptors never run | Add `withInterceptorsFromDi()` or convert them to functions |
Choosing the Order
A practical default is: logging, then request modification (auth, headers), then response handling (errors, retries), then caching last, closest to the network. Ask two questions for each interceptor. Does it need to see the request before or after others change it? Should it see errors before or after another interceptor handles them? If a retry interceptor runs before the logger in the array, the logger reports one request. If it runs after, the logger also reports one request, but its timing includes every retry attempt, because retries happen inside next. Write down why you chose your order next to the withInterceptors call.
Exercise
An interceptor contains req.headers.set('X-Client', 'web'); return next(req);. The server never receives the X-Client header. Why, and what is the corrected line?
Show answer
HttpRequest and HttpHeaders are immutable, so headers.set returns a new HttpHeaders object that the code discards, and the original request goes out unchanged. Correct it with return next(req.clone({ setHeaders: { 'X-Client': 'web' } }));.
Exercise
Interceptors are registered as withInterceptors([a, b]). In what order do a and b see the outgoing request, and in what order do their pipe operators see the response?
Show answer
The request passes through a first, then b. The response passes through b's operators first, then a's, because a wraps the Observable returned by b.
Exercise
A developer moves const router = inject(Router); inside the catchError callback of the error interceptor. What happens when a 401 arrives, and why?
Show answer
The app throws an injection-context error. The catchError callback runs asynchronously after the interceptor function has returned, outside the injection context, where inject() is not allowed. Call inject() synchronously at the top of the interceptor.
Exercise
Write a functional interceptor that adds the header Accept-Language: en only to requests whose URL starts with /api/.
Show answer
export const langInterceptor: HttpInterceptorFn = (req, next) => req.url.startsWith('/api/') ? next(req.clone({ setHeaders: { 'Accept-Language': 'en' } })) : next(req);