Sub topic 14
Advanced: Refreshing an Expired Token on 401
This chapter assumes you can write a functional interceptor, register it with withInterceptors, use inject() inside it, and read basic RxJS (catchError, switchMap, shareReplay). It builds on the authentication interceptor and the HttpContextToken from earlier chapters.
The problem
Access tokens expire on purpose, usually within minutes. When one expires, the API answers 401 Unauthorized. Without special handling, the user is sent to the login page in the middle of their work.
Most APIs issue a second, longer-lived credential, the refresh token. The client sends it to a refresh endpoint and gets a new access token. An interceptor can do this transparently. It catches the 401, gets a new token, replays the failed request, and returns the replayed response to the caller. The calling component never sees the failure.
The hard part is not the happy path. Three situations break a naive version:
- Several requests fail with 401 at the same moment, and each one starts its own refresh.
- The refresh request itself returns 401, and the interceptor tries to refresh again forever.
- The refresh fails for good (the refresh token expired too), and the app has to log the user out cleanly.
The flow
The diagram shows two concurrent requests that both hit an expired token. Only one refresh call is made.
Keeping the context tokens in one file
The earlier chapter defined SKIP_AUTH next to the auth interceptor. AuthService now needs it too, and the interceptor imports AuthService. Importing in both directions creates a circular dependency, so move the token to its own file.
// http-context.ts
import { HttpContextToken } from '@angular/common/http';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);The auth interceptor from the earlier chapter keeps working. Change its import to ./http-context.
A refresh method that runs once
The "run once" rule belongs in the service, not the interceptor. AuthService keeps the in-flight refresh observable in a field. While that field is set, every caller receives the same observable.
// auth.service.ts
import { HttpClient, HttpContext } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, finalize, map, shareReplay, tap } from 'rxjs';
import { SKIP_AUTH } from './http-context';
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly http = inject(HttpClient);
private readonly router = inject(Router);
private accessToken: string | null = null;
private refreshInFlight$: Observable<string> | null = null;
getToken(): string | null {
return this.accessToken;
}
setToken(token: string): void {
this.accessToken = token;
}
refreshToken(): Observable<string> {
if (!this.refreshInFlight$) {
this.refreshInFlight$ = this.http
.post<{ accessToken: string }>(
'/api/auth/refresh',
{},
{
withCredentials: true,
context: new HttpContext().set(SKIP_AUTH, true),
},
)
.pipe(
map((response) => response.accessToken),
tap((token) => (this.accessToken = token)),
finalize(() => (this.refreshInFlight$ = null)),
shareReplay(1),
);
}
return this.refreshInFlight$;
}
logout(): void {
this.accessToken = null;
void this.router.navigate(['/login']);
}
}Points to notice:
- The refresh call is marked
SKIP_AUTH. It must not carry the expired access token, and the refresh interceptor must not try to refresh a failed refresh. withCredentials: trueassumes the refresh token lives in anHttpOnlycookie. If your API expects the refresh token in the request body, send it there instead.shareReplay(1)lets later subscribers, such as request B above, receive the same token without a second HTTP call.finalizeclears the field once the call completes or fails, so the next expiry starts a fresh refresh.- The HTTP call completes after one response, so
shareReplay(1)does not leave a live subscription behind.
The refresh interceptor
// refresh.interceptor.ts
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, switchMap, throwError } from 'rxjs';
import { AuthService } from './auth.service';
import { SKIP_AUTH } from './http-context';
export const refreshInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
return next(req).pipe(
catchError((error: unknown) => {
const isUnauthorized =
error instanceof HttpErrorResponse && error.status === 401;
if (!isUnauthorized || req.context.get(SKIP_AUTH)) {
return throwError(() => error);
}
return auth.refreshToken().pipe(
catchError((refreshError: unknown) => {
auth.logout();
return throwError(() => refreshError);
}),
switchMap(() => next(req)),
);
}),
);
};Read it in three steps:
- Filter. Anything other than a 401, and any request marked
SKIP_AUTH, is rethrown unchanged. This is what stops the refresh loop and what keeps a wrong-password login from triggering a refresh. - Refresh.
auth.refreshToken()returns the shared observable. ThecatchErrorsits beforeswitchMap, so it handles only refresh failures. A failed refresh logs the user out and the error continues to the caller. - Retry.
switchMap(() => next(req))sends the original request again, once. The retry is inside thecatchErrorhandler, so a second 401 on the retry is not caught by the same handler. It goes to the caller, and the retry cannot loop.
inject() is called at the top of the interceptor function, which runs in an injection context. Calling it inside the catchError callback would throw, because that callback runs later, outside the context.
Registration order matters here
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { authInterceptor } from './app/auth.interceptor';
import { refreshInterceptor } from './app/refresh.interceptor';
bootstrapApplication(AppComponent, {
providers: [
provideRouter([]),
provideHttpClient(withInterceptors([refreshInterceptor, authInterceptor])),
],
});The refresh interceptor comes first, so authInterceptor sits downstream of it. When the refresh interceptor calls next(req) for the retry, the request passes through authInterceptor again. That interceptor reads getToken(), which now returns the new token, and sets the header. The retry needs no manual clone.
If you reverse the order, the retry bypasses authInterceptor. It would go out with the old header, because the refresh interceptor would be holding a request that was already cloned with the expired token. You would then have to clone the request yourself with the new token.
Edge cases
| Situation | What happens | Handling |
|---|---|---|
| Many requests fail together | Each calls `refreshToken()` | The service returns one shared observable, so one HTTP refresh call is made |
| Refresh returns 401 or 403 | `refreshToken()` errors | `logout()` runs and the caller receives the error |
| Retry returns 401 again | The error is not caught by the same `catchError` | Caller receives it, with no loop |
| Login request returns 401 | Would trigger a refresh | Mark the login request with `SKIP_AUTH` |
| Request body is a stream or a one-shot `FormData` reader | Retry may send an empty body | Avoid auto-retry for those requests, or rebuild the body |
| Request is not safe to repeat | A retried POST could run twice | The server rejected the first attempt with 401, so it normally did no work, but confirm this for your API |
| A request is already in flight when refresh finishes | It carries the old token and gets a 401 | It enters the same refresh path. The `finalize` has cleared the field, so a new refresh starts, which wastes a call |
The last row is a real, minor inefficiency. You can reduce it by comparing the token that the failed request carried against getToken() before refreshing. If the current token differs, someone already refreshed, and you can retry immediately.
Alternatives and limits
- Refresh before expiry. If the token is a JWT, you can read its
expclaim and refresh a little early. This avoids most 401s, but clock drift and revoked tokens still produce them, so you still need the reactive path in this chapter. - Non-HttpClient requests.
fetch,XMLHttpRequest, and<img>loads never reach interceptors, so they are not refreshed. - Multiple tabs. Each tab has its own
AuthService. If the server rotates refresh tokens on every use, two tabs refreshing at once can invalidate each other. Coordinate with aBroadcastChannelor a server-side grace period.
Exercise
In the refresh interceptor, why is the retry written as switchMap(() => next(req)) after a catchError that calls auth.logout(), instead of putting one catchError after the switchMap? And what would go wrong if the refresh request were not marked with SKIP_AUTH?
Show answer
A catchError placed after switchMap would also catch errors from the retried request, such as a 500 or a second 401, and treat them as refresh failures by logging the user out. Putting it before switchMap limits it to errors from refreshToken(). Without SKIP_AUTH on the refresh request, the auth interceptor would attach the expired access token to it. If the refresh endpoint returned 401, the refresh interceptor would treat that as another expired token and call refreshToken() again. Because refreshInFlight$ is still set, the request would wait on its own result, and the app would hang or loop.