HTTP Interceptors: Add Auth Tokens Automatically
Use interceptors to attach JWT tokens, handle errors, and keep HTTP code clean.
Interceptors run for every HTTP request, which is perfect for: - attaching auth tokens - handling 401 errors - logging and measuring performance ## Example: attach Authorization header ```ts 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 ```ts 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.