Angular Interceptors: Middleware for HTTP Requests
Angular Interceptors: Middleware for HTTP Requests
Angular HTTP interceptors act as middleware that can inspect, transform, and handle HTTP requests and responses globally across your application.
Common use cases for interceptors:
- Authentication: Automatically attach JWT tokens or API keys to outgoing requests
- Error handling: Centralize error responses and display user-friendly messages
- Loading indicators: Show and hide loading spinners during HTTP operations
- Caching: Cache GET requests and return cached responses when appropriate
- Logging: Log all HTTP traffic for debugging and monitoring
- Retry logic: Automatically retry failed requests with exponential backoff
Creating an interceptor:
1. Implement the HttpInterceptor interface
2. Define the intercept method that receives the request and next handler
3. Clone and modify the request as needed
4. Pass the modified request to the next handler
5. Optionally handle the response in the observable pipe
Interceptor chain ordering:
- Interceptors execute in the order they are provided
- Request modifications flow forward through the chain
- Response handling flows backward through the chain
- Each interceptor can short-circuit the chain if needed
Functional interceptors in Angular 15+:
- Use withInterceptors() with standalone APIs
- Simpler function-based approach instead of class-based
- Easier to test and compose
Interceptors are essential for maintaining clean, DRY code by centralizing cross-cutting HTTP concerns in one place.
HTTP interceptors are one of the most powerful features in Angular for cross-cutting concerns. I use them extensively for auth token injection, global error handling, and request/response logging. With functional interceptors in newer Angular, you can use withInterceptors() in provideHttpClient() which is cleaner than the class-based approach. Remember that interceptor order matters for chaining.