Skip to main content

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:
Each interceptor can:
  • Inspect and modify outgoing requests
  • Inspect and transform incoming responses
  • Handle errors
  • Retry requests
  • Cache responses
  • Block requests entirely
Angular provides HttpInterceptorFn for creating functional interceptors. This is the modern, recommended approach.

Basic interceptor

auth.interceptor.ts

Registering functional interceptors

Use withInterceptors() 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 using HttpInterceptor 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
Use context when making requests:

Interceptor order

Interceptors execute in the order they are provided:
app.config.ts
On the response path, they execute in reverse order:

Accessing dependencies

Use inject() to access services in functional interceptors:

Testing interceptors

auth.interceptor.spec.ts

Best practices

Use functional interceptorsPrefer HttpInterceptorFn over class-based interceptors for cleaner, more composable code.
Keep interceptors focusedEach interceptor should have a single responsibility. Create multiple small interceptors instead of one large one.
Always clone requests before modifying them. Requests are immutable by design.
Use context for conditional logicUse HttpContext to pass metadata to interceptors instead of checking URLs or headers.
Handle errors gracefullyInterceptors should not crash. Always handle errors and decide whether to propagate them or recover.

Next steps

Error handling

Learn how to handle HTTP errors effectively.

HttpClient

Back to HttpClient documentation.