Performance: Interceptors for authentication tokens
This affects the network request speed and page responsiveness by modifying HTTP requests and responses before they reach the server or the app.
intercept(req, next) {
return from(this.authService.getTokenAsync()).pipe(
switchMap(token => {
const authReq = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) });
return next.handle(authReq);
})
);
}intercept(req, next) {
const token = this.authService.getTokenSync();
const authReq = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) });
return next.handle(authReq);
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous token retrieval in interceptor | 0 | 0 | Blocks UI thread causing delayed input response | [X] Bad |
| Asynchronous token retrieval with RxJS in interceptor | 0 | 0 | Non-blocking, smooth UI interaction | [OK] Good |
intercept(request: HttpRequest<any>, next: HttpHandler) {
const token = 'abc123';
const cloned = request.clone({
headers: request.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(cloned);
}intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = 'xyz';
req.headers.set('Authorization', 'Bearer ' + token);
return next.handle(req);
}Pass the test and this pattern moves unknown