import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler) { const token = localStorage.getItem('authToken'); if (token) { const cloned = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }); return next.handle(cloned); } return next.handle(req); } }
This interceptor checks if a token exists in localStorage. If yes, it clones the request and adds an Authorization header with the Bearer token. This header is then sent with the request.
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('authToken');
if(token) {
const cloned = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token)
});
return next.handle(cloned);
}
return next.handle(req);
}JavaScript and TypeScript allow omitting semicolons but Angular style guide recommends them. Here, missing semicolon after localStorage.getItem('authToken') can cause issues in some setups.
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('authToken');
if (token) {
req.headers.set('Authorization', `Bearer ${token}`);
}
return next.handle(req);
}HttpRequest objects are immutable. Calling headers.set returns a new headers object but does not change the original request. The interceptor must clone the request with the new headers.
AuthInterceptor intercept(req, next) {
const token = localStorage.getItem('authToken');
if (token) {
const cloned = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) });
return next.handle(cloned);
}
return next.handle(req);
}
LoggerInterceptor intercept(req, next) {
console.log(req.headers.get('Authorization'));
return next.handle(req);
}Interceptors run in registration order. AuthInterceptor adds the header before passing the cloned request to LoggerInterceptor, so LoggerInterceptor sees the header.
Using interceptors centralizes the logic to add tokens, so you don't repeat code in every service. This makes your app easier to maintain and ensures all requests have the token.