Sub topic 5
Registering interceptors with withInterceptors
This chapter assumes you can write a basic functional interceptor, as in the previous chapters. It also assumes you know Angular dependency injection and the provideHttpClient function. Here you will learn where interceptors are registered, how the array order sets the execution order, and what goes wrong when registration is incomplete.
Why registration matters
A functional interceptor is only a function. Angular does not discover it by file name or by import. It runs only if you pass it to the provider that configures HttpClient. If you write authInterceptor and never register it, requests go out unchanged and nothing reports an error. That makes registration the first thing to check when an interceptor seems to be ignored.
The registration call
In a standalone application, you configure HttpClient once with provideHttpClient. You add interceptors by passing the result of withInterceptors as a feature argument:
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([authInterceptor, loggingInterceptor])),
],
};You then pass the config to bootstrap:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig);withInterceptors takes an array of HttpInterceptorFn values. You pass the functions themselves, not calls. Writing authInterceptor() would run the interceptor immediately with no arguments and put its return value in the array. TypeScript catches this because the types do not match.
In an application that still uses NgModule, the same call goes in the providers array of the root module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app.component';
import { authInterceptor } from './auth.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [provideHttpClient(withInterceptors([authInterceptor]))],
bootstrap: [AppComponent],
})
export class AppModule {}Do not import HttpClientModule in the same app. It is deprecated, and it adds its own HttpClient configuration that conflicts with provideHttpClient.
What the array order means
The order of the array is the order in which requests pass through the interceptors. Responses travel the same chain in reverse. With [authInterceptor, loggingInterceptor], the request meets authInterceptor first and loggingInterceptor second, then goes to the backend. The response meets loggingInterceptor first and authInterceptor second.
This ordering has a practical consequence. The logging interceptor in this chain sees the request after the auth interceptor has cloned it. It therefore logs the request with its Authorization header. If you reverse the array, the logger sees the request before the header is added.
Seeing the order yourself
The quickest way to confirm the order is to register two small interceptors that print when they run:
import { HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
function tracer(name: string): HttpInterceptorFn {
return (req, next) => {
console.log(`${name}: request out`);
return next(req).pipe(
tap({ complete: () => console.log(`${name}: response back`) }),
);
};
}
export const first = tracer('first');
export const second = tracer('second');Register them with withInterceptors([first, second]). A single successful request prints these lines:
first: request out
second: request out
second: response back
first: response backThe tracer function is a factory that returns an interceptor. This is the usual way to parameterize a functional interceptor. Only the returned function is registered, so first and second go into the array without being called.
Note that complete fires when the response stream finishes. For a normal request that is right after the final HttpResponse event. For streaming or progress-reporting requests, the stream carries more events first.
Choosing an order
The right order depends on what each interceptor needs from the others. These rules cover most cases:
- Put interceptors that change the request, such as adding headers or rewriting URLs, before interceptors that only observe it. Observers then see the final request.
- Put the logging or timing interceptor outermost (first) if you want to measure the whole chain, including time spent in the other interceptors. Put it last if you want to measure only the network call.
- Put error handling where it can see the errors you care about. An error interceptor placed first sees errors that later interceptors rethrow. It also sees errors those interceptors create.
- Put a retry interceptor so that it re-sends the request after any header changes you want repeated. Whatever is later in the array runs again on each retry. Whatever is earlier runs once.
The last point is easy to miss. Retrying re-subscribes to the observable returned by next. Interceptors later in the array run again for every attempt. Interceptors earlier in the array do not.
Registration options compared
provideHttpClient accepts several features. These are the ones related to interceptors:
| Feature | What it registers | Use it when |
|---|---|---|
| `withInterceptors([...])` | Functional interceptors | You write new interceptors as functions. |
| `withInterceptorsFromDi()` | Class interceptors provided under `HTTP_INTERCEPTORS` | You have older class-based interceptors or a library that supplies them. |
| `withRequestsMadeViaParent()` | Nothing of its own. It sends requests through the parent injector's `HttpClient`. | A lazy route or child injector configures its own `HttpClient` but should still pass through the parent's interceptors. |
You can pass more than one feature to the same provideHttpClient call. Interceptors from withInterceptorsFromDi and withInterceptors then run in the order you list the features. Class-based interceptors are covered in a later chapter.
Where you call provideHttpClient
Call provideHttpClient once, at the root, in most applications. Interceptors are tied to the injector that provides them. If a lazy route or a component calls provideHttpClient again in its own providers, that injector gets a new HttpClient. The new client's interceptor list replaces the parent's list instead of adding to it. Requests from that part of the app then skip your root interceptors, with no error.
If you do need a separate configuration there, add withRequestsMadeViaParent() to the child's provideHttpClient call. Requests then continue to the parent's HttpClient after the child's own interceptors, so the root interceptors still run.
Common registration mistakes
- Forgetting
provideHttpCliententirely.HttpClientthen fails with aNullInjectorErrorat the first injection, which is easy to diagnose. - Registering the interceptor in the wrong place. Providing it in a component's
providersdoes nothing. Only thewithInterceptorsfeature counts. - Calling the interceptor in the array. As noted above, pass the function, not its result.
- Mixing
HttpClientModuleandprovideHttpClient. PickprovideHttpClient. - Duplicating the same function in the array. It runs twice per request. Adding an
Authorizationheader twice withsetHeadersreplaces the value, so you may not notice. Appending headers withappendproduces duplicates. - Registering in the wrong order. If a logging interceptor shows no auth header, check whether it runs before the auth interceptor.
Summary of the working model
withInterceptors builds one ordered chain of functions for an injector. Each request flows through the chain from the first array element to the last, then to the backend. Each response flows back from last to first. The chain belongs to the injector that called provideHttpClient, so a second call in a child injector starts a separate chain.
Exercise
You register provideHttpClient(withInterceptors([retryInterceptor, authInterceptor])). The auth interceptor adds a token that is read fresh from AuthService on each call. A request fails with a network error and the retry interceptor re-sends it. Does the token get read again on the retry? What if you swap the array order?
Show answer
With [retryInterceptor, authInterceptor], the auth interceptor is later in the chain than the retry interceptor. Retrying re-subscribes to the observable returned by next, so everything after the retry interceptor runs again and the token is read again on each attempt. If you swap the order to [authInterceptor, retryInterceptor], the auth interceptor runs once, before the retry. Each retry re-sends the same already-cloned request with the same token.
Exercise
A lazy-loaded feature route declares providers: [provideHttpClient()]. Afterwards, requests from that feature stop carrying the Authorization header that the root authInterceptor adds. Why does this happen, and what is the fix?
Show answer
The route's injector now has its own HttpClient configuration with an empty interceptor list, and it replaces the root list for that injector. Requests made there skip the root interceptors. Either remove the extra provideHttpClient() call, or use provideHttpClient(withRequestsMadeViaParent()) so requests pass on to the parent's HttpClient and its interceptors.
Exercise
Write the registration call for three functional interceptors named a, b and c, so that a request reaches the backend after passing c, then a, then b. In what order does the response come back?
Show answer
provideHttpClient(withInterceptors([c, a, b])). The request goes through c, a, b, then the backend. The response returns through b, then a, then c.