Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 74 ยท HTTP and RxJS

HTTP Interceptors

Learn how Angular's functional HTTP interceptors add auth headers, log requests, retry failures and map errors, and how their order works.

Sooner or later every app needs the same thing to happen on every HTTP request: attach an access token, log the call, show an error toast when the server says 500, or retry when the network hiccups. Copying that code into each service is tedious and easy to forget. An HTTP interceptor is a function that sits between your code and the network, sees each request on the way out and each response on the way back, and can change either one.

This lesson builds on HttpClient: Requests and Responses and the operators from RxJS Operators You Need.

The real Angular code is read-only, because the site cannot run the Angular compiler or HttpClient. The runnable examples are stand-ins: a tiny chain of async functions with a fake backend. They show how the chain is composed and in which order things run, not Angular's implementation (which works with observables, not promises).

The shape of an interceptor

A modern interceptor is a plain function of type HttpInterceptorFn. It receives the outgoing request and a next function that passes the request to the next interceptor in line (or, for the last one, to the backend). It returns an observable of the events that come back.

TypeScript
import { HttpInterceptorFn } from '@angular/common/http';

export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('->', req.method, req.url);
  return next(req);
};

Calling next(req) is what continues the chain. If you never call it, the request never leaves the app (which is occasionally useful, for example to answer from a cache). You register interceptors when you configure the client:

TypeScript
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(
      withFetch(),
      withInterceptors([loggingInterceptor, errorInterceptor, authInterceptor, retryInterceptor]),
    ),
  ],
};

Interceptor functions run in an injection context, so you can call inject() inside them to reach services such as an AuthService. Old class-based interceptors (a class implementing HttpInterceptor) still work if you add withInterceptorsFromDi(), but new code should use functions.

Requests are immutable

You cannot change a request in place. HttpRequest objects are immutable, so you clone() them with the parts you want to replace. This guarantees that a retry sends the original request, not one that an earlier interceptor mangled.

TypeScript
import { inject } from '@angular/core';
import { HttpInterceptorFn } from '@angular/common/http';
import { AuthService } from './auth.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();

  // Never send our token to somebody else's server
  if (!token || !req.url.startsWith('/api/')) {
    return next(req);
  }
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};

The check on the URL matters. If your app also calls a third-party API, an interceptor that attaches the token to everything would leak your user's credentials to that service. Decide per request whether it should be touched, usually by looking at the URL (or at a flag, see below).

Reading and mapping responses

Because next(req) returns an observable, you can pipe RxJS operators onto it to react to what comes back. A common use is turning raw HttpErrorResponse objects into something friendlier, and redirecting on 401:

TypeScript
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const router = inject(Router);

  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        router.navigateByUrl('/login');
      }
      const message =
        error.status === 0 ? 'Network problem. Check your connection.'
        : error.status >= 500 ? 'The server had a problem. Please try again.'
        : (error.error?.message ?? 'The request failed.');
      return throwError(() => new Error(message));
    }),
  );
};

Status 0 means the browser never got an HTTP response at all (offline, DNS failure, CORS block). The interceptor still rethrows: swallowing errors would make callers believe a request succeeded.

Note that next(req) emits events, not just the final body. With the default settings you will see HttpResponse objects (and HttpHeaderResponse, progress events when you ask for them). To touch only full responses, check event instanceof HttpResponse.

Retrying

The RxJS retry operator resubscribes to the source when it errors, which for HTTP means sending the request again. A cautious retry interceptor limits itself to safe requests and certain errors, and waits longer between attempts:

TypeScript
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, timer } from 'rxjs';

export const retryInterceptor: HttpInterceptorFn = (req, next) => {
  if (req.method !== 'GET') {
    return next(req); // retrying a POST could create a duplicate
  }
  return next(req).pipe(
    retry({
      count: 3,
      delay: (error: HttpErrorResponse, attempt) => {
        const transient = error.status === 0 || error.status >= 500;
        if (!transient) {
          throw error; // 404 or 401 will not get better by asking again
        }
        return timer(2 ** attempt * 200); // 400 ms, 800 ms, 1600 ms
      },
    }),
  );
};

The delay function receives the error and the attempt number (starting at 1) and returns an observable; the retry happens when that observable emits. Throwing from it gives up immediately with that error. The point to remember is that retries multiply load on a server that may already be struggling, so keep counts small and add a delay.

Order matters

Interceptors form a chain, and the order of the array is the order a request passes through them. The response travels back through the same interceptors in reverse, like a call stack unwinding.

flowchart LR
  C["Your code"] --> L["logging"]
  L --> E["error mapping"]
  E --> A["auth"]
  A --> R["retry"]
  R --> B["Backend"]
  B -.response.-> R
  R -.-> A
  A -.-> E
  E -.-> L
  L -.-> C

Solid arrows are the request going out; dotted arrows are the response coming back through the same interceptors in reverse.

This has practical consequences:

  • Put logging first if you want to log what your code asked for, and last if you want to log exactly what hit the wire (including headers added by others).
  • Put retry inside (after) error mapping. Retry needs the raw HttpErrorResponse with its status; if an interceptor above it has already turned errors into plain Error objects, error.status is gone and the retry logic cannot tell a 503 from a 404. Error mapping sits outside, so it sees only the final failure after all retries.
  • Put auth before retry (as above), so every retried request goes out with the header attached.

There is no universally right order, but know what each interceptor will see.

Per-request switches with HttpContext

Sometimes one call needs to opt out, such as the login request (it must not carry a token that does not exist yet) or a health check that should not be retried. Instead of matching URLs everywhere, define a token and put it in the request's context:

TypeScript
import { HttpContextToken, HttpInterceptorFn } from '@angular/common/http';

export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  if (req.context.get(SKIP_AUTH)) {
    return next(req);
  }
  // ...add the header
  return next(req);
};

// In a service
this.http.post('/api/login', credentials, {
  context: new HttpContext().set(SKIP_AUTH, true),
});

The context travels with the request through every interceptor and is not sent over the network, which makes it a clean place for such metadata.

A runnable interceptor chain

The stand-in below models the mechanics. A request is a plain object, an interceptor is (req, next) => Promise<Response>, and buildChain folds the array into one function so that the first interceptor is the outermost. Each interceptor logs when it sees the request and when it sees the response, so the order is visible.

TypeScript Stand-in: building an interceptor chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You should see A, B and C on the way in, the backend, and then C, B, A on the way out. Interceptor C is the last one to change the headers, so its value wins. reduceRight is the whole trick: wrapping from the end of the array means the first element ends up outermost.

A runnable auth, retry and error-mapping stack

Now a more realistic stack on top of a flaky fake backend. It fails twice with 503, then succeeds, and has a protected route and a missing route. Delays are only logged (not waited for) so the output is instant and deterministic.

TypeScript Stand-in: auth header, retry with backoff and error mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the order: mapErrors is outside retry, so retry sees the raw statuses, retries the flaky route until it succeeds, and mapErrors only sees the final result. The /api/secret call shows the header arriving at the backend, and /api/missing shows a 404 mapped to a friendly error. (The real retry operator reacts to an error notification rather than a status code, but the ordering rule is the same.)

Try moving mapErrors to the end of the array, right next to the backend. Predict what happens to the flaky route before you run it, then re-read the order section if you were surprised.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does an interceptor call req.clone() instead of modifying the request?

    Requests are immutable. This keeps retries safe, because a retry resends the original request rather than a version altered by an earlier interceptor.
  2. 2. You register withInterceptors([a, b, c]). In which order does the response pass through them?

    The request goes a, b, c towards the backend; the response unwinds back through c, b, a, like function calls returning.
  3. 3. What is the danger of an auth interceptor that adds the token to every request without checking the URL?

    Credentials must only go to servers you own. Check the URL (or a context flag) before adding the Authorization header.
  4. 4. Why should a retry interceptor usually skip POST requests?

    If the first POST reached the server but the response was lost, a retry could create a duplicate order or payment. Retry safe, idempotent requests, or make the server idempotent.
  5. 5. What does it mean if an interceptor never calls next(req)?

    next is what continues the chain. Without it, the interceptor has to return its own response, as a cache or a mock would.

Summary

  • An interceptor is an HttpInterceptorFn: (req, next) => Observable<HttpEvent>. Register them with provideHttpClient(withInterceptors([...])); they can use inject().
  • Requests are immutable: change them with req.clone({ setHeaders: ... }).
  • Add auth headers only to your own API, and rethrow errors so callers know a request failed.
  • Retry only safe (idempotent) requests and transient errors, with a growing delay and a small count.
  • Requests run through the array in order; responses return in reverse order. The position of each interceptor changes what the others see.
  • Use an HttpContextToken to opt single requests in or out of an interceptor.
  • The Angular code in this lesson is read-only; the interceptor chains are runnable stand-ins.

Next: Signals and RxJS Interop