Sub topic 1
Angular HTTP Interceptors: Modifying Requests and Responses in One Place
Prerequisites
This chapter assumes TypeScript fundamentals, basic Angular dependency injection, and basic RxJS. You should know how to make requests with HttpClient.
Starting point: HttpClient and provideHttpClient
Angular's HttpClient sends HTTP requests and returns RxJS Observables. In a standalone Angular application, provideHttpClient() adds HttpClient to the dependency-injection system.
An interceptor is shared logic that runs between HttpClient and the server. It can inspect or change a request before sending it, then inspect the response on its way back.
What an interceptor does and where it sits
A functional interceptor receives two values:
req, the currentHttpRequestnext, a function that passes the request to the next interceptor or backend
The interceptor must call next unless it intentionally stops the request. The returned Observable contains HTTP events, including the final response.
Requests are immutable: using `clone()`
HttpRequest is immutable, meaning its existing values cannot be changed. To add a header, create a modified copy with clone().
Writing a functional interceptor
This interceptor adds an authorization header. The inject() function retrieves a service while the interceptor runs.
import { inject } from '@angular/core';
import { HttpInterceptorFn } from '@angular/common/http';
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);
};Registering interceptors with withInterceptors
Pass functional interceptors to withInterceptors() when configuring provideHttpClient().
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withInterceptors([authInterceptor]),
),
],
};With several interceptors, request processing follows array order. Response processing returns through the chain in reverse order.
Exercise
What must an interceptor do after creating a cloned request?
Show answer
It must pass the clone to next, such as return next(clonedRequest).