Token Refresh
Introduction
Section titled “Introduction”When an access token expires, the app should automatically refresh it without disrupting the user.
Pattern
Section titled “Pattern”// Auth Interceptor handles 401shandle401Error(req, next) { if (this.isRefreshing) { // Queue concurrent requests return this.refreshSubject.pipe( filter(token => token !== null), take(1), switchMap(() => next.handle(this.addAuthHeader(req))) ); }
this.isRefreshing = true; return this.authService.refreshToken().pipe( switchMap(token => { this.isRefreshing = false; this.refreshSubject.next(token); return next.handle(this.addAuthHeader(req)); }) );}Summary
Section titled “Summary”Proper token refresh handling ensures seamless authentication in Angular apps.”