Sub topic 14
Handling 401 responses in an interceptor
This chapter assumes you know HttpClient, catchError, and functional interceptors from the earlier chapters. It also assumes you have seen the retry interceptor and the retry operator. Here you will build an interceptor that reacts to one specific failure: an expired access token.
Why 401 needs its own policy
The retry interceptor from the previous chapter repeats a request when the failure is transient. A 401 response is different. It means the server does not accept your credentials, and sending the same request again fails the same way. A 401 caused by an expired access token is still recoverable. You can exchange a refresh token for a new access token and replay the original request once.
Compare the status codes that look similar:
| Status | Meaning | Correct reaction |
|---|---|---|
| 401 Unauthorized | Missing, expired, or invalid credentials | Refresh the token once, replay the request, then sign out if that fails |
| 403 Forbidden | Valid credentials, but not allowed | Show an error. A new token will not help |
| 0, 502, 503, 504 | Network or transient server problem | Use the retry policy from the previous chapters |
The interceptor therefore does three jobs:
- It attaches the current access token to outgoing requests.
- It catches a 401, refreshes the token, and replays the request exactly once.
- It ensures that many requests failing at the same time cause only one refresh call.
A service that refreshes once
The hard part is concurrency. A dashboard page may fire five requests, and all five may get a 401 within milliseconds. If each one calls the refresh endpoint, the server may reject the later calls. Many servers rotate the refresh token on each use, so the second call arrives with a token that is already spent.
The fix is to keep one in-flight refresh Observable and hand it to every caller. The shareReplay(1) operator makes all subscribers share a single HTTP call. The finalize operator clears the stored observable when the call ends, so the next expiry starts a fresh refresh.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, catchError, finalize, map, shareReplay, tap, throwError } from 'rxjs';
interface TokenResponse {
accessToken: string;
refreshToken: string;
}
@Injectable({ providedIn: 'root' })
export class AuthService {
private http = inject(HttpClient);
private router = inject(Router);
private accessToken: string | null = null;
private refreshToken: string | null = null;
private inFlightRefresh: Observable<string> | null = null;
getAccessToken(): string | null {
return this.accessToken;
}
refresh(): Observable<string> {
if (!this.inFlightRefresh) {
this.inFlightRefresh = this.http
.post<TokenResponse>('/api/auth/refresh', { refreshToken: this.refreshToken })
.pipe(
tap((tokens) => {
this.accessToken = tokens.accessToken;
this.refreshToken = tokens.refreshToken;
}),
map((tokens) => tokens.accessToken),
catchError((error: unknown) => {
this.signOut();
return throwError(() => error);
}),
finalize(() => {
this.inFlightRefresh = null;
}),
shareReplay(1)
);
}
return this.inFlightRefresh;
}
signOut(): void {
this.accessToken = null;
this.refreshToken = null;
this.router.navigate(['/login']);
}
}This sketch keeps tokens in memory, which is the safest browser location against script injection. The cost is that a page reload loses the access token. Real applications usually restore the session from an HttpOnly refresh cookie, or they accept a login after reload. Choose storage deliberately. Do not copy tokens into localStorage just to make the example survive a reload.
The interceptor
The interceptor is a function, so it follows the same rules as the retry interceptor. It receives an immutable HttpRequest and a next function. To change a request you build a modified copy with clone.
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 AUTH_URLS = ['/api/auth/login', '/api/auth/refresh'];
function withToken(req: HttpRequest<unknown>, token: string | null): HttpRequest<unknown> {
return token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
}
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
if (AUTH_URLS.some((url) => req.url.endsWith(url))) {
return next(req);
}
return next(withToken(req, auth.getAccessToken())).pipe(
catchError((error: unknown) => {
if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
return throwError(() => error);
}
return auth.refresh().pipe(switchMap((token) => next(withToken(req, token))));
})
);
};Three details make this correct.
injectruns first.inject(AuthService)works only in an injection context, which exists while the interceptor function is being called. Call it at the top, not insidecatchErroror any other async callback.- The retry sits outside
catchError. The replaynext(withToken(req, token))runs insideswitchMap, so a second 401 on the replayed request is not caught by the samecatchError. It goes to the caller as an error. This is what limits the replay to one attempt and prevents a refresh loop. - Failures pass through. Anything that is not an
HttpErrorResponsewith status 401 is rethrown unchanged, so your service-levelcatchErrorstill sees 403, 500, and network errors.
What happens when refresh fails
If the refresh call fails, refresh() signs the user out and rethrows. Every request that was waiting on the shared refresh receives the same error through switchMap. Each caller's own catchError can then show its error state, as covered in the chapter on user feedback. The router has already moved to /login, so the component usually does not need to do more than stop its loading indicator.
Be careful about which failures mean "sign out". A 401 or 400 from the refresh endpoint means the refresh token is no longer valid. A network error or a 503 means only that the server could not be reached. The sketch above signs out on any refresh failure, which is simple but harsh. A less aggressive version checks error.status inside the catchError in refresh() and signs out only for 400 and 401. In that version a transient failure leaves the session intact.
Registering the interceptor and ordering
Interceptors run in the order listed, and the response travels back through them in reverse. Place the retry interceptor first and the auth interceptor second:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { retryInterceptor } from './retry.interceptor';
import { authInterceptor } from './auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter([]),
provideHttpClient(withInterceptors([retryInterceptor, authInterceptor])),
],
};With this order, every retry attempt passes through authInterceptor again. Each attempt carries the current token, even if another request refreshed it a moment earlier. The retry interceptor sees a 401 only after the auth interceptor has already tried to recover, and 401 is not in RETRYABLE_STATUSES, so it is not retried a second time.
Replaying non-idempotent requests
The retry interceptor refuses to repeat POST requests because the server might already have processed them. A 401 is the exception. The server rejected the request at the authentication step, before running the handler, so replaying a POST after a refresh does not duplicate work. That holds for a standard setup. If a gateway authenticates after the work has begun, check your own backend before relying on it.
One more limit applies to bodies. A replayed request reuses the same body object. This is fine for JSON, but a FormData or other stream-like body is not guaranteed to survive being sent twice. Test file uploads separately.
Testing the single refresh
The most valuable test checks that two simultaneous 401 responses produce exactly one refresh call and that both requests are replayed with the new token. expectOne fails if it finds zero or several matching requests, so it enforces the "only one" part for you.
import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { authInterceptor } from './auth.interceptor';
describe('authInterceptor', () => {
let http: HttpClient;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideRouter([]),
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('refreshes once and replays both failed requests', () => {
const results: string[] = [];
http.get<string>('/api/a').subscribe((r) => results.push(r));
http.get<string>('/api/b').subscribe((r) => results.push(r));
const unauthorized = { status: 401, statusText: 'Unauthorized' };
httpMock.expectOne('/api/a').flush(null, unauthorized);
httpMock.expectOne('/api/b').flush(null, unauthorized);
httpMock
.expectOne('/api/auth/refresh')
.flush({ accessToken: 'new-token', refreshToken: 'next-refresh' });
const replayA = httpMock.expectOne('/api/a');
const replayB = httpMock.expectOne('/api/b');
expect(replayA.request.headers.get('Authorization')).toBe('Bearer new-token');
expect(replayB.request.headers.get('Authorization')).toBe('Bearer new-token');
replayA.flush('A');
replayB.flush('B');
expect(results).toEqual(['A', 'B']);
});
});Add a second test where the refresh endpoint answers 401 and assert that both callers receive an error. Add a third where the replayed request returns 401 again and assert that /api/auth/refresh was requested only once.
Common mistakes
- Refreshing on every 401 without sharing. Parallel requests then race, and rotating refresh tokens break.
- Forgetting to exclude the refresh URL. This causes an endless loop, as the warning above explains.
- Mutating the request.
req.headers.set(...)does not change the request. Headers and the request are immutable, so useclone. - Treating 403 like 401. Refreshing a token does not grant permission.
- Catching the replay error in the same pipe. Placing the replay outside
switchMapor inside the samecatchErrorcan allow a second refresh round.
Exercise
Two requests receive a 401 at nearly the same time. Which line in AuthService.refresh() makes both of them wait for a single refresh call, and what happens to inFlightRefresh afterwards?
Show answer
shareReplay(1) makes both subscribers share one HTTP call, because the second caller gets the stored inFlightRefresh observable instead of creating a new one. The finalize callback sets inFlightRefresh back to null when the call completes or fails, so the next token expiry starts a new refresh.
Exercise
The replayed request in authInterceptor also returns 401. Why does the interceptor not enter a refresh loop, and where does the error go?
Show answer
The replay next(withToken(req, token)) runs inside switchMap, which is downstream of the catchError that handles the first 401. That catchError does not see errors from the replay. The second 401 therefore goes to the caller as an HttpErrorResponse, and no further refresh happens.