HTTP Interceptors — Angular

An interceptor is a function HttpInterceptorFn = (req, next) => ... that every HttpClient request passes through, registered once with…

Every request to Jali's server needs a login token in its header. Writing that header in every service, one by one, makes it easy to forget in one of them.

An HTTP interceptor writes it once for all of them. It's a function that every HttpClient request passes through before it reaches the server, and every response passes on its way back. Picture the counter in front of Jali's Pancake Stall's kitchen. Every order slip, from any waiter, goes through that counter first. The clerk never writes on the original slip: he makes a copy stamped "PAID", and the copy goes into the kitchen. He also tallies on a board how many orders are cooking, and if the kitchen shouts "the stove died, again!", he hands the order in once more before telling the waiter it failed.

The shape of an interceptor

// src/app/interceptors.ts
import { HttpInterceptorFn } from '@angular/common/http'

export const logInterceptor: HttpInterceptorFn = (req, next) => {
  console.log(req.method, req.url) // GET /api/orders/17
  return next(req)
}

A request can't be changed: forward the copy

HttpRequest is immutable: once created, its contents can't change. To add a header, make a copy with req.clone():

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token() // 'jali-123', or null when logged out
  if (!token) {
    return next(req)
  }
  const authReq = req.clone({
    setHeaders: { Authorization: `Bearer ${token}` },
  })
  return next(authReq)
}

These three versions were run in the Playground. Here's what the server received:

authInterceptor Server receives Authorization Server's answer
return next(authReq) Bearer jali-123 200
return next(req) null 401
req.headers.set('Authorization', ...) then next(req) null 401

The second row is the most common trap: the copy is made, then thrown away. The server receives Authorization = null and answers 401. The third row fails for the same reason: HttpHeaders is immutable too, set() returns a new headers object, and the result is never used. Assigning req.headers = ... doesn't even compile: TS2540: Cannot assign to 'headers' because it is a read-only property.

Registering them, and their order

Interceptors are registered once in app.config.ts, inside provideHttpClient:

// src/app/app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http'
import { authInterceptor, loadingInterceptor, errorInterceptor } from './interceptors'

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

One click on Check order #17 status (GET /api/orders/17) prints this in the Playground console, in this order:

auth: request copy given Authorization
loading: 1 request running
server: GET /api/orders/17, Authorization = Bearer jali-123
server: answers 200
page: order #17 cooking
loading: 0 requests running

A loading counter

@Injectable({ providedIn: 'root' })
export class LoadingService {
  running = signal(0)
}

export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
  const loading = inject(LoadingService)
  loading.running.update((n) => n + 1)
  return next(req).pipe(
    finalize(() => loading.running.update((n) => n - 1)),
  )
}

The header's template just writes @if (loading.running() > 0) { <p>Processing...</p> }. Why a number and not true/false? Click Check status twice, quickly: the counter goes 1, 2, 1, 0. With a boolean, the first request to finish would switch Processing... off while the second is still running. finalize is called at every ending: success, failure, or cancellation.

Errors: catchError and retry

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const router = inject(Router)
  return next(req).pipe(
    retry(1),
    catchError((err: HttpErrorResponse) => {
      if (err.status === 401) {
        router.navigate(['/login'])
      }
      return throwError(() => err)
    }),
  )
}
Situation Attempts at the server What the page shows
Busy server (first attempt 500), no retry 500 Failed: Http failure response for /api/orders/17: 500 Internal Server Error
Busy server, with retry(1) 500, 200 Order #17: cooking
Logged out, with retry(1) 401, 401 Failed: Http failure response for /api/orders/17: 401 Unauthorized

The last row is wasteful: a 401 will be refused again. To repeat only server errors, use the config form: retry({ count: 1, delay: (err: HttpErrorResponse) => (err.status >= 500 ? timer(500) : throwError(() => err)) }). With it, a 401 passes straight on, and a 500 is tried again after 500 ms.

📌 In the Playground: a fake server

The Playground has no server and doesn't read app.config.ts. So the Lab's code adds a fourth interceptor, fakeServer, that never calls next() and answers like the server: 401 without the header, 500 on the first attempt when the server is busy, otherwise 200. Its body is wrapped in defer() so it answers once per subscribe, like a real request; that's what retry(1) repeats. The interceptor list is installed through createEnvironmentInjector([provideHttpClient(withInterceptors([...]))], ...). In a CLI project, app.config.ts is enough, and fakeServer goes.

Older code sometimes uses class interceptors (implements HttpInterceptor, registered through HTTP_INTERCEPTORS and withInterceptorsFromDi()). The idea is the same; for new code, use the function form.

⚠️ Tokens lost on the way, and wasted retries

TL;DR: An interceptor is a function HttpInterceptorFn = (req, next) => ... that every HttpClient request passes through, registered once with provideHttpClient(withInterceptors([...])). A request passes in array order, its response comes back in reverse. HttpRequest is immutable: add a header with req.clone({ setHeaders: { Authorization: ... } }) and forward the copy to next(); next(req) sends the request without the header (the server answers 401). Common patterns: auth adds the token, a loading counter goes up as a request passes and down in finalize, and an error interceptor uses catchError (say, 401 to /login) and retry for server errors.

⚡ One function for every request

Write:

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

Meaning: Every HttpClient request passes the interceptors on its way out, and every response passes them again on its way back. So one interceptor can add a token or handle errors for the whole app. Register it once with provideHttpClient(withInterceptors([...])).

In the exercise, use the HttpInterceptorFn type, put Authorization inside setHeaders, and pass what clone returns to next().

⚡ Forward the copy

Guess first: req.clone(...) is made, but the code says return next(req). What header does the server receive?

Authorization is empty (null), and the server answers 401. The copy is made, then thrown away, because clone doesn't change req.

Meaning: HttpRequest is immutable: it can't change once created. Add a header through req.clone(), then forward the copy: next(authReq).

⚡ Requests go forward, responses come back

Write:

provideHttpClient(withInterceptors([authInterceptor, loadingInterceptor, errorInterceptor]))

Meaning: A request passes in array order: auth, loading, error, then the server. The response comes back in reverse order. An interceptor placed before auth doesn't see the header yet.

What you will learn