Overview
HTTP interceptors provide a mechanism to intercept and modify HTTP requests and responses globally. They act as middleware in the HTTP request pipeline, allowing you to implement cross-cutting concerns like authentication, logging, caching, and error handling.How interceptors work
Interceptors are called in the order they are provided and form a chain:- Inspect and modify outgoing requests
- Inspect and transform incoming responses
- Handle errors
- Retry requests
- Cache responses
- Block requests entirely
Functional interceptors (recommended)
Angular providesHttpInterceptorFn for creating functional interceptors. This is the modern, recommended approach.
Basic interceptor
auth.interceptor.ts
Registering functional interceptors
UsewithInterceptors() when providing HttpClient:
app.config.ts
Common use cases
Authentication token
Add authentication tokens to all requests:auth.interceptor.ts
Logging
Log all HTTP requests and responses:logging.interceptor.ts
Loading indicator
Show a loading spinner during HTTP requests:loading.interceptor.ts
loading.service.ts
Caching
Cache GET requests:cache.interceptor.ts
API prefix
Add base URL to all requests:api-prefix.interceptor.ts
Retry logic
Automatically retry failed requests:retry.interceptor.ts
Class-based interceptors (legacy)
The older class-based approach usingHttpInterceptor interface is still supported but not recommended for new code.
Creating a class-based interceptor
auth.interceptor.ts
Registering class-based interceptors
app.config.ts
Modifying requests
Requests are immutable, so you must clone them to make changes:Modifying responses
Transform response data:transform-response.interceptor.ts
Conditional interception
Apply interceptor logic conditionally:conditional.interceptor.ts
Interceptor order
Interceptors execute in the order they are provided:app.config.ts
Accessing dependencies
Useinject() to access services in functional interceptors:
Testing interceptors
auth.interceptor.spec.ts
Best practices
Next steps
Error handling
Learn how to handle HTTP errors effectively.
HttpClient
Back to HttpClient documentation.
