Sub topic 14
Handling 401 Responses in an Interceptor
This chapter assumes you know catchError, functional interceptors registered with withInterceptors, and the difference between HttpErrorResponse status codes. You will build one interceptor that attaches an access token, reacts to a 401, refreshes the token once, and replays the failed request.
Why 401 is different
A 401 Unauthorized response usually means the access token has expired. It does not mean the request is wrong. The right response is neither to show an error nor to blindly retry. You get a new token first and then repeat the request.
This does not fit the retry interceptor from the previous chapter. That interceptor repeats the same request, and a repeat with the same expired token fails the same way. A 401 needs a different action between attempts, so give it its own interceptor.
The flow
Sharing one refresh
If a page fires five requests and all five get a 401, you must not call the refresh endpoint five times. Most servers rotate refresh tokens, so the second call can invalidate the first. The service below keeps one in-flight refresh and hands it to every caller.
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> {
if (!this.refresh$) {
this.refresh$ = this.http
.post<{ accessToken: string }>('/api/auth/refresh', {})
.pipe(
map((res) => res.accessToken),
tap((token) => (this.token = token)),
finalize(() => (this.refresh$ = null)),
shareReplay(1)
);
}
return this.refresh$;
}
}shareReplay(1) lets late callers join the same request. finalize clears the field once the refresh finishes, so the next expiry starts a new one.
The interceptor
import { HttpErrorResponse, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, switchMap, throwError } from 'rxjs';
import { AuthService } from './auth.service';
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);
const router = inject(Router);
if (req.url.startsWith('/api/auth/')) {
return next(req);
}
return next(withToken(req, auth.getToken())).pipe(
catchError((error: unknown) => {
if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
return throwError(() => error);
}
return auth.refreshToken().pipe(
catchError((refreshError: unknown) => {
void router.navigate(['/login']);
return throwError(() => refreshError);
}),
switchMap((token) => next(withToken(req, token)))
);
})
);
};Register it with provideHttpClient(withInterceptors([authInterceptor, retryInterceptor])). Order matters here. Interceptors run in array order on the way out and in reverse on the way back.
Pitfalls
- Refresh loops. The
/api/auth/check keeps a failing refresh call from triggering another refresh. Without it, a 401 from the refresh endpoint recurses forever. - Redirecting on the wrong error. The refresh
catchErrorsits beforeswitchMap, so it handles only refresh failures. A 500 on the replayed request goes to the caller and does not send the user to the login page. - Replaying once only. If the replayed request returns 401 again, the error propagates. It is not refreshed a second time.
Exercise
Five requests fail with 401 at the same moment. Which line in AuthService makes sure only one refresh call is sent, and what clears it afterward?
Show answer
shareReplay(1) combined with the cached refresh$ field means all five callers subscribe to the same in-flight refresh observable. The finalize operator sets refresh$ back to null when the refresh finishes, so the next token expiry starts a new refresh.