Sub topic 9
Functional interceptors with withInterceptors
This chapter assumes you can write an Angular service that calls HttpClient, and that you know pipe(), tap and catchError from RxJS. It shows where cross-cutting HTTP logic belongs, so the retry and error policies in later chapters need no changes in individual services.
What an interceptor is
An interceptor is a function that sits between HttpClient and the network. Every request passes through it on the way out, and every response or error passes through it on the way back. You can read a request, change it, observe the result, or replace the result.
A functional interceptor has the type HttpInterceptorFn. It takes two arguments:
req: the outgoingHttpRequest.next: a function that passes the request to the next interceptor, or to the backend if none is left. It returns anObservableof HTTP events.
You must call next(req) to let the request continue. If you never call it, the request is never sent.
A request-modifying interceptor
Requests are immutable. To change one, call clone() and pass the copy to next.
import { HttpInterceptorFn } from '@angular/common/http';
export const clientHeaderInterceptor: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith('/api/')) {
return next(req);
}
const cloned = req.clone({ setHeaders: { 'X-Client': 'web' } });
return next(cloned);
};Requests to other URLs, such as third-party APIs, pass through untouched. Checking the URL is how you keep an interceptor from leaking headers to hosts you do not control.
A response-observing interceptor
Because next(req) returns an Observable, you can attach operators to it. Errors arrive in the error channel as HttpErrorResponse, the same as in a service.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const errorLogInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
tap({
error: (error: unknown) => {
if (error instanceof HttpErrorResponse) {
console.warn(`${req.method} ${req.url} failed with status ${error.status}`);
}
},
})
);
};tap only observes. The error still reaches the caller. To change or swallow the error you would use catchError instead.
Registering with withInterceptors
Register interceptors once, in provideHttpClient.
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { clientHeaderInterceptor } from './client-header.interceptor';
import { errorLogInterceptor } from './error-log.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([clientHeaderInterceptor, errorLogInterceptor])),
],
};The array order matters. Requests flow through the array from first to last. Responses and errors flow back from last to first.
This order decides which interceptor sees the final error. When you add a retry interceptor later, its position relative to a logging interceptor determines whether you log every failed attempt or only the final one.
Common mistakes
- Not calling
next. The request hangs or never goes out. Every code path must returnnext(...)or a deliberate replacement Observable. - Mutating the request. Assigning to
reqproperties fails. Usereq.clone(). - Mixing styles.
withInterceptorsaccepts only functions. Class-based interceptors registered withHTTP_INTERCEPTORSneedwithInterceptorsFromDi()instead. - Forgetting the scope. An interceptor applies to every
HttpClientcall. Filter by URL or method inside the function when the policy should not apply to all of them.
Exercise
You register withInterceptors([a, b, c]). In what order does a response pass through the interceptors, and what happens if b never calls next(req)?
Show answer
Responses pass through c, then b, then a, the reverse of the request order. If b never calls next(req), the request never reaches c or the backend. Only the Observable that b returns reaches the caller, so b must return one deliberately.