angular
/

Angular Interceptors – Global HTTP Middleware

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

angular

Angular Interceptors – Global HTTP Middleware

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.

  1. 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.

TypeScriptRead-only
1
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');

  // Clone the request to add the new header
  const authReq = req.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`
    }
  });

  // Pass the cloned request instead of the original
  return next(authReq);
};

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.

  1. 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.

  1. 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.

TypeScriptRead-only
1
import { provideHttpClient, withInterceptors } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(
      withInterceptors([loggingInterceptor, authInterceptor, errorInterceptor])
    )
  ]
};

Interceptor Comparison

FeatureClass-Based (Legacy)Functional (Modern)
DefinitionClass implementing HttpInterceptorHttpInterceptorFn
RegistrationHTTP_INTERCEPTORS multi-providerwithInterceptors() array
BoilerplateHigh (Requires @Injectable)Low (Pure function)
DI AccessConstructor injectionUse the inject() function
PerformanceStandardHighly optimized / Tree-shakable

Test Your Knowledge

Q1
of 3

Which method is used to modify an outgoing HttpRequest in an interceptor?

A
req.update()
B
req.clone()
C
req.set()
D
req.modify()
Q2
of 3

What is the correct order of execution for interceptors during a response?

A
The same order they were registered
B
The reverse order they were registered
C
Randomly
D
Only the first one registered executes
Q3
of 3

Which helper function is used to add functional interceptors to the provideHttpClient provider?

A
addInterceptors()
B
useInterceptors()
C
withInterceptors()
D
injectInterceptors()

Frequently Asked Questions

Why do I have to clone the request?

HttpRequest and HttpResponse objects in Angular are immutable to ensure they are thread-safe and to prevent side effects in a reactive stream. Cloning ensures that the original request remains untouched as it moves through the pipeline.

Can I skip an interceptor for a specific request?

Yes. You can use 'HttpContext' tokens to pass metadata with a request. Your interceptor can check for a specific token (e.g., 'BYPASS_AUTH') and simply return 'next(req)' without modifying it.

What is 'next' in the interceptor function?

'next' represents the next interceptor in the chain. If there are no more interceptors, it represents the final backend handler that actually performs the HTTP request.

Previous

angular http client

Next

angular error handling

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.