Sub topic 14
Advanced: refreshing an expired token on 401
This chapter assumes you can write a functional interceptor, clone a request, and use catchError and switchMap. It builds on the authorization header interceptor from earlier in the tutorial.
The problem
Access tokens expire. When one does, the backend answers 401 Unauthorized. Instead of sending the user to the login page, the app can ask for a new access token with a refresh token, then repeat the failed request. An interceptor is a good place for this because every request already passes through it.
The interceptor has to do four things:
- Send the request with the current token.
- If the response is a 401, request a new token.
- Repeat the original request with the new token.
- If several requests fail at once, refresh only once.
The flow
Sharing one refresh
Suppose a page fires five requests with an expired token. All five get a 401, and without care you would call the refresh endpoint five times. Many backends rotate refresh tokens, so the second call can fail and log the user out.
The fix is to keep the in-flight refresh as an observable in the service. Every caller subscribes to that same observable.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, finalize, map, shareReplay, tap } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthService {
private http = inject(HttpClient);
private token: string | null = null;
private refresh$: Observable<string> | null = null;
getToken(): string | null {
return this.token;
}
refreshToken(): Observable<string> {
this.refresh$ ??= this.http
.post<{ accessToken: string }>('/auth/refresh', {})
.pipe(
map((res) => res.accessToken),
tap((token) => (this.token = token)),
finalize(() => (this.refresh$ = null)),
shareReplay(1),
);
return this.refresh$;
}
}shareReplay(1) makes all subscribers share one HTTP call. finalize clears the stored observable when the call ends, so the next expiry starts a fresh refresh.
The interceptor
import { HttpErrorResponse, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, switchMap, throwError } from 'rxjs';
import { AuthService } from './auth.service';
const withToken = (req: HttpRequest<unknown>, token: string | null) =>
token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
export const refreshInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
return next(withToken(req, auth.getToken())).pipe(
catchError((error: unknown) => {
const isRefreshCall = req.url.includes('/auth/refresh');
if (!(error instanceof HttpErrorResponse) || error.status !== 401 || isRefreshCall) {
return throwError(() => error);
}
return auth.refreshToken().pipe(
switchMap((newToken) => next(withToken(req, newToken))),
);
}),
);
};Register it with withInterceptors([refreshInterceptor]). It replaces the plain authInterceptor, because it also attaches the header.
What to check
- Call
inject()first. It runs at the top of the interceptor, inside the injection context. Inside thecatchErrorcallback it would throw. - Skip the refresh endpoint. If
/auth/refreshitself returns 401, the check onisRefreshCallstops an infinite loop. The error reaches the caller instead. - Handle a failed refresh. If the refresh call fails, the error flows to the caller. Add a
catchErrorinrefreshToken()that clears the token and navigates to the login page. - Retry once. The retried request calls
nextdirectly, not throughcatchErroragain, so a second 401 is returned as an error. - Be careful with non-idempotent requests. Repeating a
POSTis safe here because the first attempt was rejected before it was processed. Still, confirm that your backend behaves this way.
Exercise
Five requests fail with 401 at the same moment. Which two pieces of the code above ensure the refresh endpoint is called only once, and why does the observable need to be cleared afterwards?
Show answer
The refresh$ ??= check returns the stored observable to later callers instead of creating a new request, and shareReplay(1) lets all of them share one HTTP call and its result. finalize sets refresh$ back to null when the call ends. Without that, the next token expiry would reuse the old, already completed observable and replay the stale token instead of requesting a new one.