javascript / expert
Snippet
Functional Interceptor for Secure Token Rotation
Modern Angular uses functional HTTP interceptors for a more lightweight and composable middleware architecture. This snippet demonstrates how to inject an authentication service into an interceptor to dynamically append bearer tokens to outgoing requests, a critical pattern for secure API communication.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { HttpInterceptorFn, HttpRequest, HttpHandlerFn, inject } from '@angular/common/http';import { AuthService } from './auth.service';import { switchMap, take } from 'rxjs';export const authInterceptor: HttpInterceptorFn = (req, next) => {const authService = inject(AuthService);return authService.token$.pipe(take(1),switchMap(token => {const clonedReq = req.clone({setHeaders: { Authorization: `Bearer ${token}` }});return next(clonedReq);}));};
angular
Breakdown
1
export const authInterceptor: HttpInterceptorFn = (req, next) => {
Defines a stateless functional interceptor instead of a traditional class-based one.
2
req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
Immutably clones the request to add security headers before passing it down the chain.