Sub topic 4
Writing a functional interceptor
This chapter assumes you know TypeScript, Angular services and dependency injection, basic HttpClient calls, and RxJS basics such as pipe and tap. By the end you can write a functional interceptor and explain what it receives and what it must return.
The shape of an interceptor
A functional interceptor is a plain function of type HttpInterceptorFn. Angular calls it for every request that goes through HttpClient. It receives two arguments:
req: the outgoingHttpRequest.next: a function that hands a request to the next step in the chain. The last step sends the request to the backend.
The function must return an Observable of HttpEvent. The simplest case just forwards the request:
import { HttpInterceptorFn } from '@angular/common/http';
export const noopInterceptor: HttpInterceptorFn = (req, next) => {
return next(req);
};Calling next(req) returns the observable for the rest of the chain. Returning it gives the response stream back to the caller.
Changing the request
An HttpRequest is immutable, so you cannot assign to its properties. Call clone() with the fields you want to change and pass the clone to next:
import { HttpInterceptorFn } from '@angular/common/http';
export const appHeaderInterceptor: HttpInterceptorFn = (req, next) => {
const modified = req.clone({
setHeaders: { 'X-App-Version': '1.0.0' },
});
return next(modified);
};The original req stays unchanged. Every later step in the chain sees the clone.
Changing the response
next(req) returns an observable, so you work on the response with RxJS operators. The stream can emit several HttpEvent objects per request, and the final one is an HttpResponse. This interceptor adds a header to each response:
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { map } from 'rxjs';
export const responseTagInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
map((event) => {
if (event.type === HttpEventType.Response) {
return event.clone({ headers: event.headers.set('X-Handled', 'true') });
}
return event;
}),
);
};Responses are immutable too, which is why the code uses event.clone(). The code must also return the non-response events unchanged. If map returned nothing for them, upload and download progress events would be lost.
Skipping the network
You do not have to call next. An interceptor can answer a request itself by returning an observable that emits a response:
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
export const offlineStubInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.endsWith('/api/ping')) {
return of(new HttpResponse({ status: 200, body: { ok: true } }));
}
return next(req);
};A request to /api/ping never reaches the backend. All other requests continue down the chain.
Registering it
An interceptor does nothing until you register it in provideHttpClient(withInterceptors([...])). The next chapter covers registration and ordering.
Common errors
- Forgetting to call
next. If a code path neither callsnextnor returns another observable, the request never completes. The caller waits forever or gets a type error. - Mutating the request. Writing
req.headers = ...fails to compile, and mutating headers in place does not work either. Useclone(). - Dropping events. A
maporfilteron the response stream that discards non-Responseevents breaks progress reporting. - Swallowing the result. Calling
next(req).subscribe()and returning something else sends the request twice or returns the wrong stream. Return the observable fromnext.
Exercise
A teammate writes (req, next) => { req.clone({ setHeaders: { 'X-Trace': '1' } }); return next(req); }. The backend never receives the X-Trace header. Why, and how do you fix it?
Show answer
clone() returns a new request and does not change req. The code throws the clone away and forwards the original. Fix it by passing the clone on: const traced = req.clone({ setHeaders: { 'X-Trace': '1' } }); return next(traced);.