What are Interceptors?
Interceptors are a powerful architectural tool in Angular that allow you to sit in the middle of the communication between your application and the backend server. As a Technical Lead, you can think of them as 'Middleware' for your HTTP requests and responses. They allow you to transform outgoing requests (like adding an Auth token) or process incoming responses (like handling 401 errors) in one centralized location rather than repeating logic in every service.
- Functional Interceptors (Modern Standard)
In modern Angular (v15+), interceptors are written as simple functions (HttpInterceptorFn). This is more efficient and easier to test than the older class-based approach. Because HTTP requests are immutable, you must 'clone' a request if you wish to modify it before passing it to the next handler.
The Interceptor Pipeline
Interceptors form a chain. When you make a request, it passes through each interceptor in the order they were provided. When the response comes back from the server, it travels back through the same chain in reverse order.
- Common Use Cases
- Authentication: Automatically attaching a JWT Bearer token to every API call.
- Logging: Timing how long requests take to identify slow backend endpoints.
- Error Handling: Catching 401 (Unauthorized) or 500 (Server Error) responses globally to redirect users or show alerts.
- Loading Spinners: Incrementing a counter when a request starts and decrementing it when it finishes to show a global progress bar.
- Caching: Checking if a response for a specific URL is already in memory before hitting the network.
- Registering Interceptors
Interceptors must be registered in your application configuration using the withInterceptors helper. This ensures that the Angular HttpClient knows to pipe every request through your custom functions.
Interceptor Comparison
| Feature | Class-Based (Legacy) | Functional (Modern) |
|---|---|---|
| Definition | Class implementing HttpInterceptor | HttpInterceptorFn |
| Registration | HTTP_INTERCEPTORS multi-provider | withInterceptors() array |
| Boilerplate | High (Requires @Injectable) | Low (Pure function) |
| DI Access | Constructor injection | Use the inject() function |
| Performance | Standard | Highly optimized / Tree-shakable |