Angular15 min read
HTTP Interceptors: Add Auth Tokens Automatically
Use interceptors to attach JWT tokens, handle errors, and keep HTTP code clean.
Dylan Peterson
September 4, 2025
3.7k137
Interceptors run for every HTTP request, which is perfect for:
- attaching auth tokens
- handling 401 errors
- logging and measuring performance
Example: attach Authorization header
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('token');
if (!token) return next(req);
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
return next(authReq);
};
Provide it
import { provideHttpClient, withInterceptors } from '@angular/common/http';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
],
});
Why it’s important
Without interceptors, you repeat token logic in every API call. Interceptors centralize it.
Next: RxJS operators, make API flows cleaner with map and switchMap.
#Angular#HTTP#Intermediate