0
0
Angularframework~8 mins

Interceptors for authentication tokens in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Interceptors for authentication tokens
MEDIUM IMPACT
This affects the network request speed and page responsiveness by modifying HTTP requests and responses before they reach the server or the app.
Adding authentication tokens to HTTP requests
Angular
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);
    })
  );
}
Asynchronous token retrieval avoids blocking the main thread and allows requests to proceed smoothly.
📈 Performance GainNon-blocking requests improve input responsiveness (INP) and reduce UI delays
Adding authentication tokens to HTTP requests
Angular
intercept(req, next) {
  const token = this.authService.getTokenSync();
  const authReq = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) });
  return next.handle(authReq);
}
Synchronous token retrieval blocks the interceptor, delaying all HTTP requests and hurting responsiveness.
📉 Performance CostBlocks rendering for 50-100ms per request depending on token retrieval speed
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous token retrieval in interceptor00Blocks UI thread causing delayed input response[X] Bad
Asynchronous token retrieval with RxJS in interceptor00Non-blocking, smooth UI interaction[OK] Good
Rendering Pipeline
Interceptors modify HTTP requests before they are sent and responses before they are processed, affecting network timing and UI update speed.
Network Request
JavaScript Execution
UI Update
⚠️ BottleneckJavaScript Execution when synchronous blocking occurs
Core Web Vital Affected
INP
This affects the network request speed and page responsiveness by modifying HTTP requests and responses before they reach the server or the app.
Optimization Tips
1Avoid synchronous token retrieval in interceptors to prevent blocking HTTP requests.
2Use asynchronous methods like RxJS to fetch tokens without blocking the UI thread.
3Keep interceptor logic minimal to reduce JavaScript execution time and improve responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of retrieving authentication tokens synchronously in an Angular interceptor?
AIt blocks the main thread delaying all HTTP requests and UI updates.
BIt increases the bundle size significantly.
CIt causes layout shifts on the page.
DIt reduces the number of HTTP requests.
DevTools: Performance
How to check: Record a performance profile while triggering HTTP requests. Look for long tasks or blocking scripts during request interception.
What to look for: Check for long JavaScript execution times in the flame chart indicating blocking synchronous token retrieval.