Sub topic 13
Class-based interceptors and migrating from HTTP_INTERCEPTORS
Before Angular 15 introduced functional interceptors, every interceptor was a class. Many existing code bases still use that style. This chapter explains how class-based interceptors work, how they interact with functional ones, and how to migrate them one at a time.
This chapter assumes you know TypeScript, Angular services and dependency injection, and basic RxJS (pipe, tap, catchError). It also assumes you have read the earlier chapters on functional interceptors and withInterceptors.
Why you still need to read class-based interceptors
Class-based interceptors are not removed. Angular still supports them, and they work in both standalone and NgModule applications. You will meet them in three situations:
- You maintain an application written before functional interceptors existed.
- A third-party library ships an interceptor class and asks you to register it with
HTTP_INTERCEPTORS. - You want to move to functional interceptors and need to do it without breaking the app.
The functional style is the recommended style for new code. It is shorter, and its order of execution is easier to predict, as the sections below show.
Anatomy of a class-based interceptor
A class-based interceptor is an injectable class that implements the HttpInterceptor interface. The interface has one method, intercept. It receives the request and an HttpHandler, and it returns an observable of events.
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class LegacyInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(req);
}
}
// Registration:
// provideHttpClient(withInterceptorsFromDi()),
// { provide: HTTP_INTERCEPTORS, useClass: LegacyInterceptor, multi: true }The pieces map directly onto what you already know:
| Class-based | Functional |
|---|---|
| `intercept(req, next)` method | The function `(req, next) => ...` |
| `next.handle(req)` | `next(req)` |
| Dependencies through the constructor | Dependencies through `inject()` |
| Registered with the `HTTP_INTERCEPTORS` token | Registered in `withInterceptors([...])` |
The rules do not change. The request is immutable, so you call req.clone() to change it. You must call next.handle or the request never leaves the application. The returned observable emits HttpEvent values, and you can transform it with RxJS operators.
Dependencies through the constructor
A class gets its services through the constructor, as any Angular class does. Because the interceptor is created by the dependency injection system, constructor injection works normally.
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthClassInterceptor implements HttpInterceptor {
constructor(private readonly auth: AuthService) {}
intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const token = this.auth.getToken();
if (!token) {
return next.handle(req);
}
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
});
return next.handle(authReq);
}
}This is the class equivalent of the authInterceptor function you wrote earlier. Note the @Injectable() decorator. Without it, Angular cannot construct the class with its constructor arguments.
Registering class-based interceptors
Registration has two parts. Both are required.
- Call
provideHttpClient(withInterceptorsFromDi()). This tellsHttpClientto read interceptors from the dependency injection system. - Add a provider for the
HTTP_INTERCEPTORStoken withmulti: truefor each class.
import { bootstrapApplication } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { AuthClassInterceptor } from './app/auth-class.interceptor';
import { LegacyInterceptor } from './app/legacy.interceptor';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(withInterceptorsFromDi()),
{ provide: HTTP_INTERCEPTORS, useClass: AuthClassInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: LegacyInterceptor, multi: true },
],
});The multi: true flag matters. It makes Angular collect every provider for the token into an array instead of letting the last one replace the others. Class interceptors run in the order of that array: the first provider sees the request first, and the response comes back through the providers in reverse.
What happens if you forget withInterceptorsFromDi
If you call provideHttpClient() without withInterceptorsFromDi(), the HTTP_INTERCEPTORS providers are ignored. There is no error and no warning. Requests simply go out without your interceptors. This is the most common reason a migrated app suddenly stops sending its auth header.
NgModule applications
In an application that still uses NgModule, the older registration looked like this:
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthClassInterceptor } from './auth-class.interceptor';
@NgModule({
imports: [HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthClassInterceptor, multi: true },
],
})
export class AppModule {}HttpClientModule is deprecated in current Angular versions. The replacement is provideHttpClient(...), which you can also use in the providers array of an NgModule. When you switch, add withInterceptorsFromDi() so the existing HTTP_INTERCEPTORS providers keep working.
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { AuthClassInterceptor } from './auth-class.interceptor';
@NgModule({
providers: [
provideHttpClient(withInterceptorsFromDi()),
{ provide: HTTP_INTERCEPTORS, useClass: AuthClassInterceptor, multi: true },
],
})
export class AppModule {}This one change is a safe first migration step. Behavior stays the same, and you stop depending on the deprecated module.
Mixing functional and class-based interceptors
You can use both styles in one application during a migration. Pass both features to provideHttpClient:
import { provideHttpClient, withInterceptors, withInterceptorsFromDi } from '@angular/common/http';
import { loggingInterceptor } from './app/logging.interceptor';
provideHttpClient(
withInterceptors([loggingInterceptor]),
withInterceptorsFromDi(),
)Angular does not interleave the two lists. It runs all interceptors registered through withInterceptors first, in array order, and then runs the interceptors from HTTP_INTERCEPTORS. The order of the two with... calls inside provideHttpClient does not change this. Responses travel back in the reverse direction as usual.
This fixed ordering is the main hazard of a partial migration. Suppose your class-based AuthClassInterceptor adds a header and a new functional loggingInterceptor should log that header. The functional interceptor runs first, so it sees the request before the header exists. If order matters between two interceptors, migrate them together, or move the one that must run first into the functional list.
Migrating step by step
Migrate one interceptor at a time and keep the application working after each step. The sequence below keeps risk low.
- Switch from
HttpClientModuletoprovideHttpClient(withInterceptorsFromDi()). Do not change any interceptor yet. - Pick an interceptor with no ordering constraints, such as a logging interceptor.
- Rewrite it as a function. Replace constructor injection with
inject(),next.handle(req)withnext(req), and the class body with the function body. - Remove its
HTTP_INTERCEPTORSprovider and add the function towithInterceptors([...]). - Run the tests for the code that makes HTTP calls. Fix any order differences described above.
- Repeat until
HTTP_INTERCEPTORShas no entries. Then removewithInterceptorsFromDi().
Here is the class from earlier, rewritten:
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).getToken();
if (!token) {
return next(req);
}
return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};Two details are worth checking during the rewrite:
- A class can keep state in fields, for example a counter of in-flight requests. A function has no instance. Move such state into an injectable service and read it with
inject(). - A class can have helper methods. In a function interceptor, define helpers as plain functions in the same file.
Testing during a migration
Tests written with HttpTestingController do not care which style an interceptor uses. They care only about registration. A test for a class-based interceptor needs the same two registration parts as production code:
import { TestBed } from '@angular/core/testing';
import { HTTP_INTERCEPTORS, HttpClient, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { AuthClassInterceptor } from './auth-class.interceptor';
import { AuthService } from './auth.service';
describe('AuthClassInterceptor', () => {
it('adds the Authorization header', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
{ provide: HTTP_INTERCEPTORS, useClass: AuthClassInterceptor, multi: true },
{ provide: AuthService, useValue: { getToken: () => 'abc' } },
],
});
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/data').subscribe();
const req = controller.expectOne('/api/data');
expect(req.request.headers.get('Authorization')).toBe('Bearer abc');
req.flush({});
controller.verify();
});
});When you migrate the interceptor, the assertions stay the same. Only the providers array changes: replace withInterceptorsFromDi() and the HTTP_INTERCEPTORS entry with withInterceptors([authInterceptor]). Passing tests before and after the change is good evidence that the migration did not alter behavior.
Edge cases and gotchas
- Interceptor instances are singletons. A class interceptor is created once by the injector that provides it. Do not store per-request data in its fields.
- Provider scope.
HTTP_INTERCEPTORSentries are read from the injector whereprovideHttpClientis configured. Providing them in a lazy-loaded route's injector does not add them to a rootHttpClient. HttpClientModulein a lazy module. Importing the module again in a lazy-loadedNgModulecreates a separateHttpClientthat may not see the root interceptors. Prefer a singleprovideHttpClientat the root.- Third-party classes. If a library gives you only a class, keep it registered through
HTTP_INTERCEPTORS. You do not need to rewrite code you do not own. - Duplicate registration. Listing the same class twice with
multi: trueruns it twice. This produces duplicate headers or repeated logging.
Summary of the decision
| Situation | Choice |
|---|---|
| New interceptor in your own code | Functional, in `withInterceptors` |
| Existing class you maintain | Migrate gradually using the steps above |
| Class from a third-party library | Keep it in `HTTP_INTERCEPTORS` with `withInterceptorsFromDi()` |
| Order between a class and a function matters | Move both to functional, or accept that functions run first |
Exercise
An app calls provideHttpClient(withInterceptors([loggingInterceptor]), withInterceptorsFromDi()) and also provides AuthClassInterceptor through HTTP_INTERCEPTORS. The logging interceptor prints the request headers, but the Authorization header never appears in the log even though the server receives it. Why, and what are two ways to fix it?
Show answer
Functional interceptors from withInterceptors always run before the class-based interceptors from HTTP_INTERCEPTORS, regardless of the order of the with... calls. The logging interceptor sees the request before AuthClassInterceptor adds the header. Fix one: migrate AuthClassInterceptor to a functional interceptor and list it before loggingInterceptor in withInterceptors. Fix two: move the logging into the response path, for example log event.url and status in a tap on the response, or log the final request from a class interceptor registered after AuthClassInterceptor.
Exercise
After moving an app from HttpClientModule to provideHttpClient(), no class-based interceptor runs any more, and there are no errors. What is missing?
Show answer
The call needs the withInterceptorsFromDi() feature: provideHttpClient(withInterceptorsFromDi()). Without it, HttpClient ignores providers for HTTP_INTERCEPTORS.