← Back to Angular, page 10

angular-0189 · Hard senior

Write an interceptor that refreshes an expired access token on a 401 response, makes only one refresh call when several requests fail together, and retries the failed requests.

On a 401, start one refresh request and share it with every request that fails while it is in flight (a stored shared observable, cleared when it finishes). Each failed request waits for the shared result, then retries once with the new token. If refresh fails, clear the session and send the user to login.

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:

  1. Attach the token. The interceptor clones each API request with Authorization: Bearer <token>.
  2. Catch 401. Use catchError on the response. Only handle HttpErrorResponse with status 401, only for your API, and never for the refresh request itself (or you would loop).
  3. Share one refresh. Keep a field refresh$: Observable<string> | null in the auth service. If it is null, create it: http.post('/auth/refresh', ...), map to the new token, store the token, and pipe shareReplay(1) and finalize(() => this.refresh$ = null). If it already exists, reuse it. All failing requests subscribe to the same observable.
  4. Retry once. After the refresh emits, switchMap to next(withToken(req, newToken)). Mark the retried request (for example with an HttpContextToken RETRIED) so a second 401 does not start another refresh, and instead logs the user out.
  5. Refresh failure. If the refresh call fails (refresh token expired), clear the session, navigate to login with a return URL, and propagate the error.
  6. 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.

typescript
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.