← Back to Angular, page 2

angular-0026 · Medium mid

How do you write functional HTTP interceptors for authentication and error handling, and in what order do they run?

A functional interceptor is a function of type HttpInterceptorFn that receives the request and a next handler. Register interceptors with provideHttpClient(withInterceptors([...])). Requests are immutable, so you clone them to change them. Requests pass through the list in order and responses come back in reverse.

Full answer

An interceptor sits between your code and the network. It can change every outgoing request or every response without touching each service. Typical jobs are adding an auth header, showing a global error message, logging, or retrying.

A modern interceptor is a function:

ts
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};

It runs in an injection context, so inject() works. HttpRequest objects are immutable. To change one you call clone(). The returned Observable is the response stream, so operators such as catchError can run on it.

Registration: provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])). Order: for a request, the first interceptor runs first and the last runs closest to the network. For the response, the order is reversed. This is like walking into a building through several doors and leaving through the same doors in reverse.

Class-based interceptors (implements HttpInterceptor, registered with the HTTP_INTERCEPTORS token) are legacy. They can still be used with withInterceptorsFromDi().

Security care: add the token only to your own API origin, not to every URL, or you will leak the token to third parties. Another trap is blindly handling 401 by refreshing the token in many parallel requests. Use a single shared refresh, usually with shareReplay.

A global error interceptor should rethrow the error (throwError) after reporting it, so calling code can still react.

typescript
// file: auth.service.ts
import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AuthService {
  readonly token = signal<string | null>(null);
}

// file: interceptors.ts
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
import { AuthService } from './auth.service';

const API_PREFIX = '/api/';

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

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const router = inject(Router);
  return next(req).pipe(
    catchError((error: unknown) => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        void router.navigate(['/login']);
      }
      return throwError(() => error);
    }),
  );
};

// file: app.config.ts
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { authInterceptor, errorInterceptor } from './interceptors';

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

Angular 20.3. The auth interceptor only touches requests that start with the API prefix. The error interceptor rethrows.

Key points

  • Interceptors are `HttpInterceptorFn` functions, registered with `withInterceptors([...])`.
  • Requests are immutable, so use `req.clone(...)`.
  • Order: request goes first to last, response goes last to first.
  • Attach tokens only to your own API, and rethrow errors after handling them.

Common mistakes

  • Adding the `Authorization` header to every request, including third-party URLs.
  • Swallowing the error in the interceptor so the caller thinks the call succeeded.
  • Modifying `req.headers` directly. It is immutable and the change is ignored.

Follow-ups

  • How would you skip the auth header for one specific request?
  • How do you avoid many parallel token refreshes?
  • How do class-based interceptors differ?

Tips

  • Mention origin checks for the token. It is a security point that stands out.
  • Draw the doors-in-and-out picture for the order question.
  • Say that rethrowing preserves the caller's error handling.

Evaluation rubric

  • Writes a functional interceptor with clone.
  • States ordering correctly.
  • Handles errors and token scope safely.