HTTP Interceptors

HTTP Interceptors

When communicating with secure APIs, you often need to attach an Authentication Token to the header of every single request.

Manually adding the token to hundreds of different this.http.get() calls throughout your app is tedious and error-prone.

To automate this, Angular provides HTTP Interceptors.


What is an Interceptor?

An interceptor acts as a middleman between your application and the backend server.

It intercepts all outgoing HTTP requests, allowing you to seamlessly clone the request and append authorization headers!

It can also intercept incoming HTTP responses to handle global errors (like logging users out if they receive a 401 Unauthorized error).


The Functional Interceptor

In modern Angular, interceptors are created as simple, straightforward functions using HttpInterceptorFn.

You take the original request (req), clone it to add your custom headers, and pass it to the next handler.

Interceptor Function Example:

import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => { // Get the token from local storage const authToken = localStorage.getItem('token');

// Clone the request and inject the authorization header const clonedRequest = req.clone({ setHeaders: { Authorization: Bearer ${authToken} } });

// Pass the modified request forward return next(clonedRequest); };


Providing the Interceptor

Just creating the function isn't enough; you must tell Angular to actually use it.

If you are using a standalone application, you register it in main.ts using the withInterceptors() configuration option inside provideHttpClient().

Registering Interceptors:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';

bootstrapApplication(AppComponent, { providers: [ // Tells the HttpClient to push every request through our auth function! provideHttpClient(withInterceptors([authInterceptor])) ] });


Exercise 1 of 2

?

What is the primary, most common use case for an HTTP Interceptor in an enterprise Angular application?

Exercise 2 of 2

?

Why must you 'clone' the original HTTP request (req.clone) inside the interceptor function?