Full answer
When an access token expires, a page often has several requests in flight. If each one starts its own refresh, the server may see several refresh calls, and with rotating refresh tokens only the first succeeds and the others fail, logging the user out by mistake. The pattern that solves it is single flight: one refresh, many waiters.
Design:
- Attach the token. The interceptor clones each API request with
Authorization: Bearer <token>. - Catch 401. Use
catchErroron the response. Only handleHttpErrorResponsewith status 401, only for your API, and never for the refresh request itself (or you would loop). - Share one refresh. Keep a field
refresh$: Observable<string> | nullin the auth service. If it isnull, create it:http.post('/auth/refresh', ...), map to the new token, store the token, and pipeshareReplay(1)andfinalize(() => this.refresh$ = null). If it already exists, reuse it. All failing requests subscribe to the same observable. - Retry once. After the refresh emits,
switchMaptonext(withToken(req, newToken)). Mark the retried request (for example with anHttpContextTokenRETRIED) so a second 401 does not start another refresh, and instead logs the user out. - Refresh failure. If the refresh call fails (refresh token expired), clear the session, navigate to login with a return URL, and propagate the error.
- Proactive refresh (optional). Refresh slightly before expiry using the token's expiry time, to avoid most 401 responses. Keep the 401 handler anyway for clock differences and revoked sessions.
Edge cases: a request that starts while a refresh is running still sends the old token and gets a 401, but it then joins the same shared refresh and retries, so it works. Making new requests wait for a running refresh before they are sent saves that extra failed call, and is an optional improvement. Non-idempotent requests (POST) can be retried safely after a 401 because the server rejected them before processing. Do not retry other errors here.
Test with HttpTestingController: make three calls, answer them with 401, expect exactly one refresh request, flush it, then expect three retried requests with the new token.
import { HttpClient, HttpContextToken, HttpErrorResponse, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { Injectable, inject, signal } from '@angular/core';
import { Observable, catchError, finalize, map, shareReplay, switchMap, tap, throwError } from 'rxjs';
const RETRIED = new HttpContextToken<boolean>(() => false);
@Injectable({ providedIn: 'root' })
export class AuthTokens {
private readonly http = inject(HttpClient);
readonly token = signal<string | null>('old-token');
private refresh$: Observable<string> | null = null;
refresh(): Observable<string> {
if (!this.refresh$) {
this.refresh$ = this.http.post<{ token: string }>('/auth/refresh', {}).pipe(
map((r) => r.token),
tap((token) => this.token.set(token)),
catchError((error) => {
this.token.set(null); // session is over
return throwError(() => error);
}),
finalize(() => (this.refresh$ = null)),
shareReplay(1),
);
}
return this.refresh$;
}
}
const withToken = (req: HttpRequest<unknown>, token: string | null) =>
token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
export const refreshInterceptor: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith('/api/')) {
return next(req); // refresh calls and third party calls are left alone
}
const auth = inject(AuthTokens);
return next(withToken(req, auth.token())).pipe(
catchError((error: unknown) => {
if (!(error instanceof HttpErrorResponse) || error.status !== 401 || req.context.get(RETRIED)) {
return throwError(() => error);
}
return auth.refresh().pipe(
switchMap((token) => next(withToken(req.clone({ context: req.context.set(RETRIED, true) }), token))),
);
}),
);
};Angular 20.3, type-checked. A Karma test with `HttpTestingController` sends three parallel requests that get 401, checks that exactly one refresh request is made, then checks that all three are retried with the new token. A second test checks that a failed refresh clears the session.
Key points
- Several parallel 401 responses must cause one refresh request (single flight).
- Store the shared refresh observable in the auth service, clear it in `finalize`.
- Retry each request once with the new token, and guard against loops with a context flag.
- If refresh fails, clear the session and go to login.
Common mistakes
- Each failed request starting its own refresh.
- Retrying the refresh request itself on 401 and looping.
- Retrying forever when the new token is also rejected.
Follow-ups
- Why can parallel refresh calls log the user out with rotating refresh tokens?
- How would you refresh before the token expires?
- Where do you keep the refresh token?
Tips
- Name the race condition first.
- Describe the shared observable and its clean-up.
- Say how you test it with `HttpTestingController`.
Evaluation rubric
- Prevents duplicate refresh calls.
- Retries once and prevents loops.
- Handles refresh failure and describes a test.