Sub topic 2
How Interceptor Order Affects Requests and Responses
Assume you know TypeScript, Angular dependency injection, HttpClient, Observables, and pipe, tap, and catchError.
Request and response order
Angular builds an interceptor chain from the array passed to withInterceptors. Requests travel through the array from first to last. Responses travel back from last to first.
flowchart TD
A[HttpClient request] --> B[authInterceptor]
B --> C[loggingInterceptor]
C --> D[Backend]
D --> E[loggingInterceptor response handling]
E --> F[authInterceptor response handling]
F --> G[Subscriber]For example, with [authInterceptor, loggingInterceptor]:
- The authentication interceptor receives the request first.
- The logging interceptor receives the cloned request with its header.
- The backend handles the request.
- The logging interceptor observes the response first.
- The authentication interceptor observes it last.
This nesting resembles function calls. Each interceptor must call next, or the request stops at that point.
Injecting services and adding authorization
A functional interceptor runs in an Angular injection context. Use inject() inside the interceptor to obtain a service. Since HttpRequest is immutable, use clone() to create a changed request.
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);
}
const authenticatedRequest = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
return next(authenticatedRequest);
};Register the interceptors in the intended order:
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
import { loggingInterceptor } from './logging.interceptor';
export const appConfig = {
providers: [
provideHttpClient(
withInterceptors([authInterceptor, loggingInterceptor]),
),
],
};Logging responses and timing
next(req) returns an Observable of HttpEvent values. A request can produce several events, so check for the final Response event before logging its status.
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = Date.now();
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
const elapsed = Date.now() - started;
console.log(`${req.method} ${req.urlWithParams} -> ${event.status} in ${elapsed}ms`);
}
}),
);
};Exercise
With [authInterceptor, loggingInterceptor], which interceptor handles the response first?
Show answer
loggingInterceptor handles the response first because responses travel through the chain in reverse order.