Angular › HTTP Client & Interceptors

What is an HTTP interceptor in Angular, and what is it commonly used for?

Intermediate

Answer

An interceptor lets you intercept every outgoing HTTP request and incoming response, allowing you to modify them consistently in one central place, such as automatically adding an authentication token to every request's headers or logging every response for debugging.
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const authReq = req.clone({
    headers: req.headers.set('Authorization', `Bearer ${getToken()}`)
  });
  return next(authReq);
};
Real-world example An app automatically attaches the current user's authentication token to every single API request using one shared interceptor, instead of manually adding that header inside every single service method individually.

Common follow-ups: Why must the request object be cloned rather than modified directly inside an interceptor?;How would you register this interceptor so it applies to every HTTP request in the app?