Angular › HTTP Client & Interceptors
What is an HTTP interceptor in Angular, and what is it commonly used for?
IntermediateAnswer
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.