Sub topic 9
Functional interceptors with withInterceptors
This chapter assumes you can write an Angular service that calls HttpClient, you know what pipe() and catchError do, and you have seen inject(). Earlier chapters handled errors inside each service method. That approach repeats code in every method. An interceptor lets you apply one policy, such as adding headers, logging failures, or retrying, to every request in one place.
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. Every response, or error, passes back through it on the way in.
In current Angular you write an interceptor as a plain function of type HttpInterceptorFn:
type HttpInterceptorFn = (
req: HttpRequest<unknown>,
next: HttpHandlerFn
) => Observable<HttpEvent<unknown>>;The function receives two arguments:
reqis the outgoing request.nextis a function that passes a request to the next interceptor, or to the backend if there are no more.
It returns an Observable of HTTP events. You decide what that Observable is. You can return next(req) unchanged, return a modified version, or return something else entirely.
Registering with withInterceptors
You register interceptors once, in the application config, as a feature of provideHttpClient:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
import { loggingInterceptor } from './logging.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([loggingInterceptor, authInterceptor])),
],
};withInterceptors takes an array of functions. The array order is the execution order, so it matters. The next section covers it.
Your first interceptor: adding a header
Requests are immutable. You cannot assign req.headers = .... You call req.clone() with the properties you want to change and pass the clone to next.
This interceptor adds a bearer token to calls to your own API. It reads the token from a small service:
// auth.service.ts
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthService {
readonly token = signal<string | null>(null);
}// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token();
if (!token || !req.url.startsWith('/api/')) {
return next(req);
}
return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};Two details here:
- The
startsWith('/api/')check stops the token from leaking to third-party URLs. An interceptor sees every request, so scope it deliberately. inject()works because Angular runs the interceptor function in an injection context. That context lasts only while the function body runs synchronously. Callinject()at the top, not inside atapcallback or asetTimeout. A later call throws an error.
Order of execution
Interceptors form a chain. With withInterceptors([a, b, c]), the request travels a, then b, then c, then the backend. The response travels back in the opposite direction: c, b, a.
Interceptor A sees the original request and the final response. Interceptor C sees the request after A and B have changed it, and it sees the raw response first. This has practical consequences for error handling.
| Placement | Sees the request | Sees the response or error | Good for |
|---|---|---|---|
| First in the array (outermost) | The original, unmodified request | The final result after all other interceptors | Retry, global error mapping, loading indicators |
| Middle | Request as modified by earlier interceptors | Result before outer interceptors process it | Logging, caching |
| Last (innermost) | The request with all headers added | The raw backend result | Timing the actual network call |
Working with the response
next(req) returns an Observable of HttpEvent values. For a normal request that Observable emits an HttpResponse (plus progress events if you ask for them) and then completes. If the request fails, it errors with an HttpErrorResponse. That is the same error type you handled with catchError in services, so the same tools apply.
This interceptor logs failures and rethrows them unchanged:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = performance.now();
return next(req).pipe(
catchError((error: unknown) => {
const ms = Math.round(performance.now() - started);
if (error instanceof HttpErrorResponse) {
console.warn(`${req.method} ${req.urlWithParams} failed with ${error.status} after ${ms} ms`);
}
return throwError(() => error);
})
);
};Rethrowing the original error keeps this interceptor transparent. A service downstream can still read error.status. If you instead convert the error to a plain Error, as the service in an earlier chapter did, every caller loses access to the status. Decide in one place which layer maps errors.
To inspect successful responses, use tap and check event instanceof HttpResponse. Do not assume every emitted event is a response.
Short-circuiting
An interceptor does not have to call next. If it returns its own Observable, the request never reaches the network. A cache or an offline stub works this way:
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
export const offlineStubInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url === '/api/ping') {
return of(new HttpResponse({ status: 200, body: { ok: true } }));
}
return next(req);
};The of(...) Observable emits one event and completes, which is the shape HttpClient expects.
Per-request options with HttpContext
Sometimes one request needs to opt out of a global policy. A search-as-you-type call should not be retried, for example. You should not do this by checking URL strings inside the interceptor. Angular provides HttpContext, a typed bag of values that travels with a request and that interceptors can read but that is never sent over the wire.
import { HttpClient, HttpContext, HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
export const SKIP_RETRY = new HttpContextToken<boolean>(() => false);
export const policyInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(SKIP_RETRY)) {
return next(req);
}
// ...apply retry logic here
return next(req);
};
export function searchUsers(term: string) {
const http = inject(HttpClient);
return http.get('/api/users', {
params: { q: term },
context: new HttpContext().set(SKIP_RETRY, true),
});
}The factory passed to HttpContextToken provides the default, so requests that set nothing get false. You will use this pattern when you build the retry interceptor in the next chapter.
Gotchas
- Downstream function bodies run once. When a retry interceptor calls
retryonnext(req), a failed attempt resubscribes to the same Observable. The body of a later interceptor, such as the line that reads the token inauthInterceptor, does not run again. Only the Observable it returned is resubscribed. If a retried request needs a fresh token, put the auth interceptor before the retry interceptor, or wrap the call indefer(() => next(req)). - Interceptors run for every request. That includes requests made by libraries that use
HttpClient. Scope by URL or byHttpContext. - Do not mutate the request. Always
clone(). Headers and params objects are immutable too, so usesetHeaders,setParams, orheaders.set(...)on a clone. - Class-based interceptors are separate. Older
HttpInterceptorclasses registered throughHTTP_INTERCEPTORSonly run if you addwithInterceptorsFromDi(). Mixing both styles is possible but harder to reason about, so migrate when you can. - Errors thrown synchronously. If your interceptor throws before returning an Observable, the error surfaces in the caller's
errorchannel only in some paths. Prefer returningthrowError(() => ...)so failure always travels through the Observable.
Exercises
Exercise
You register provideHttpClient(withInterceptors([a, b, c])). In what order does each interceptor see the request, and in what order does each see the response?
Show answer
The request passes through a, then b, then c, then the backend. The response passes back through c, then b, then a. So a is the outermost interceptor: it sees the original request and the final response or error.
Exercise
An interceptor contains return next(req).pipe(tap(() => { const auth = inject(AuthService); })). Why does this fail, and how do you fix it?
Show answer
inject() only works in an injection context, which exists while the interceptor function body runs synchronously. The tap callback runs later, when a response arrives, so inject() throws. Move const auth = inject(AuthService); to the top of the interceptor function, outside any callback, and use auth inside tap.
Exercise
Write the header of an interceptor that adds X-Request-Id: abc to every request. What must you call, and why can't you just set the header on req?
Show answer
export const idInterceptor: HttpInterceptorFn = (req, next) => next(req.clone({ setHeaders: { 'X-Request-Id': 'abc' } })); Requests are immutable, so you create a modified copy with clone() and pass that copy to next.