---
title: "Angular HTTP Interceptors: Auth, Token Refresh, Retries and Error Handling"
description: "Functional HTTP interceptors in Angular: attaching tokens, refreshing expired tokens once, safe retries, central error handling and skipping interceptors per request."
url: https://sanderyaz.com/en/blog/angular-http-interceptors/
author: Sander Yazıcıoğlu
date: 2026-12-04
updated: 2026-12-04
lang: en
tags: ["Angular","TypeScript","Frontend","RxJS"]
---

# Angular HTTP Interceptors: Auth, Token Refresh, Retries and Error Handling

Every Angular app I have worked on at Testinium ended up with the same cross-cutting HTTP needs: add a token to every call, refresh it when it expires, retry a flaky request, show one error toast instead of fifty. During the Angular 7 to 20 upgrades, the class-based interceptors that did this were some of the last pieces to migrate. Here is how I write them today as functional interceptors, and the traps I hit on the way.

## The shape of a functional interceptor

Since Angular 15, an interceptor can be a plain function. It receives the request and a `next` handler, and returns an `Observable` of events. Because it runs in an injection context, `inject()` works inside it.

```ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthStore).accessToken();
  if (!token || !req.url.startsWith('/api/')) return next(req);
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};
```

Requests are immutable, so you always `clone()`. Note the URL check: without it you will happily send your token to a third-party CDN or analytics endpoint.

Register them in order:

```ts
provideHttpClient(
  withInterceptors([authInterceptor, errorInterceptor, refreshInterceptor, retryInterceptor]),
);
```

Order matters. The request passes through the list top to bottom, and the response comes back bottom to top. With this order, `retryInterceptor` is the innermost layer, so it retries first; `errorInterceptor` sits outside it and only sees an error once the retries are exhausted. Swap the two and users get an error toast for every failed attempt, even the ones a retry fixed. I keep a comment above this array explaining the order, because someone will reorder it alphabetically one day.

If you are mid-migration and still have class-based interceptors, `withInterceptorsFromDi()` keeps them working next to the new ones. The [standalone migration guide](/en/blog/angular-standalone-migration/) covers that step.

## Refreshing an expired token exactly once

The classic bug: the access token expires, five parallel requests get `401`, and the app fires five refresh calls. Some refresh servers rotate refresh tokens, so four of those five calls fail and the user is logged out.

The fix is to share one in-flight refresh between all callers:

```ts
let refresh$: Observable<string> | null = null;

export const refreshInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  return next(req).pipe(
    catchError((err: unknown) => {
      if (!(err instanceof HttpErrorResponse) || err.status !== 401 || req.url.endsWith('/auth/refresh')) {
        return throwError(() => err);
      }
      refresh$ ??= auth.refresh().pipe(
        finalize(() => (refresh$ = null)),
        shareReplay(1),
      );
      return refresh$.pipe(
        switchMap((token) => next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }))),
      );
    }),
  );
};
```

Three details make this work:

- `shareReplay(1)` turns the refresh into one shared call that late subscribers also get.
- `finalize` clears it, so the next expiry triggers a fresh refresh.
- The refresh endpoint itself is excluded, otherwise a failed refresh recurses forever.

If the refresh fails, log the user out in one place (the auth service), not in every interceptor.

## Retrying without causing damage

Retrying a `GET` that hit a gateway timeout is fine. Retrying a `POST /payments` is how you charge someone twice. I only retry idempotent methods and only on transient statuses:

```ts
const RETRYABLE = new Set([0, 502, 503, 504]);

export const retryInterceptor: HttpInterceptorFn = (req, next) => {
  if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next(req);
  return next(req).pipe(
    retry({
      count: 2,
      delay: (err, attempt) =>
        err instanceof HttpErrorResponse && RETRYABLE.has(err.status)
          ? timer(300 * 2 ** attempt)
          : throwError(() => err),
    }),
  );
};
```

Status `0` means the request never got a response (network drop, CORS failure). Exponential backoff keeps a struggling backend from being hammered by your own retries.

## Central error handling

One interceptor maps errors to user-facing messages and sends unexpected ones to monitoring. Components then only handle the errors they actually care about, such as a `409` conflict on a form.

```ts
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const toast = inject(ToastService);
  return next(req).pipe(
    catchError((err: unknown) => {
      if (err instanceof HttpErrorResponse && err.status >= 500) {
        toast.error('Something went wrong. Please try again.');
      }
      return throwError(() => err);
    }),
  );
};
```

Always rethrow. Swallowing the error here means the component's `subscribe` never learns the call failed and a spinner spins forever. For sending the unexpected ones to a tracker with readable stack traces, see [frontend error monitoring](/en/blog/frontend-error-monitoring-source-maps/).

## Skipping an interceptor per request

Some calls must not get the global treatment: a background poll should not show toasts, a login call should not trigger refresh. Use `HttpContextToken` instead of magic headers:

```ts
export const SILENT = new HttpContextToken<boolean>(() => false);

this.http.get('/api/status', { context: new HttpContext().set(SILENT, true) });

// inside errorInterceptor
if (req.context.get(SILENT)) return throwError(() => err);
```

Context tokens are typed, never leave the browser, and are easy to search for.

## Testing interceptors

With `provideHttpClientTesting()` you can assert what the interceptor did to the request:

```ts
TestBed.configureTestingModule({
  providers: [provideHttpClient(withInterceptors([authInterceptor])), provideHttpClientTesting()],
});
http.get('/api/runs').subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/api/runs');
expect(req.request.headers.get('Authorization')).toBe('Bearer abc');
```

For the refresh interceptor, fire two requests, flush both with `401`, and assert that `expectOne('/api/auth/refresh')` passes. That single test has caught regressions for me more than once. More patterns are in [Angular component testing](/en/blog/angular-component-testing/).

## Conclusion

Keep each interceptor small and single-purpose, write down the order, share one in-flight token refresh, retry only idempotent requests, and always rethrow errors. Use `HttpContextToken` for exceptions instead of special headers. Done this way, interceptors stay boring, which is exactly what you want from code that touches every request.

---

About the author: [Sander Yazıcıoğlu](https://sanderyaz.com/en/about/). Sander Yazıcıoğlu is a Senior Full-Stack Developer in Istanbul. At LiveTesting he builds the backend, frontend, realtime systems and Appium automation of a real-device testing platform; before that he built enterprise Angular apps at Testinium and Loadium.
