Sub topic 2
What an interceptor does and where it sits
This chapter assumes you know TypeScript, Angular services and dependency injection, how to call HttpClient.get() and post(), and the basics of RxJS (Observable, pipe, tap). It builds the working model of an interceptor. Later chapters cover cloning, registration, ordering and the individual use cases in detail.
The problem interceptors solve
Most applications repeat the same HTTP logic everywhere. Every call needs an Authorization header. Every failure should be logged. Every slow call should be timed. You could put this logic in each service method, but then each new method has to remember to include it, and changing the logic means editing many files.
An HTTP interceptor is a function that HttpClient runs for every request it sends. Each one can look at the outgoing request, change it, and look at or change what comes back. The shared logic lives in one place.
Where an interceptor sits
HttpClient does not send requests itself. It builds an HttpRequest object and hands it to a chain of handlers. The last handler in the chain is the backend, which does the real network work (XMLHttpRequest by default, or fetch if you enable it with withFetch()). Interceptors are the handlers placed before the backend.
The interceptor is therefore a middleman with two jobs:
- On the way out, it receives the request and decides what to pass on.
- On the way back, it receives the stream of events from the rest of the chain and decides what to pass to the caller.
Your services and components stay unaware of it. They call http.get() and get a result.
The smallest interceptor
A functional interceptor has the type HttpInterceptorFn. It takes two arguments: the request req, and a function next that forwards the request to the next handler in the chain. It returns an Observable of HTTP events.
import { HttpInterceptorFn } from '@angular/common/http';
export const noopInterceptor: HttpInterceptorFn = (req, next) => {
return next(req);
};This interceptor changes nothing. It receives req, passes it to next, and returns what next returns. Every real interceptor is a variation on this shape: do something with req before calling next, and do something with the returned observable after.
A request has to be registered with provideHttpClient(withInterceptors([...])) before the chain runs it. The next chapters cover registration. Here the focus is on what the function sees.
What `next` returns
next(req) returns Observable<HttpEvent<unknown>>. The type matters because it is not an observable of response bodies. An HttpEvent is one of several kinds of event, and each has a type property from the HttpEventType enum.
| Event type | When it appears |
|---|---|
| `Sent` | The request has been handed to the network layer. |
| `UploadProgress` / `DownloadProgress` | Only when the caller sets `reportProgress: true`. |
| `ResponseHeader` | Headers arrived before the body (progress-reporting calls). |
| `Response` | The full response, as an `HttpResponse` with `status`, `headers` and `body`. |
A typical call such as http.get<User[]>('/api/users') makes HttpClient filter this stream down to the body, so your service sees an array of users. The interceptor sits below that filtering, so it sees the raw events. This is why interceptor code that inspects responses checks event.type === HttpEventType.Response before reading status. The loggingInterceptor chapter shows this in practice.
Failures arrive differently. A failed request does not appear as an event. The observable errors with an HttpErrorResponse, so you handle it with catchError rather than tap.
The chain is lazy and runs per subscription
HttpClient methods return cold observables. Calling http.get('/api/data') does not run any interceptor or send anything. The chain runs when someone subscribes, and it runs again for each subscription.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class DataService {
private readonly http = inject(HttpClient);
load() {
const request$ = this.http.get('/api/data'); // nothing has run yet
request$.subscribe(); // interceptors run, one request is sent
request$.subscribe(); // interceptors run again, a second request is sent
}
}This has two consequences. Side effects that you put before next(req) run once per subscription, not once per http.get() call. And an interceptor that is never reached because nobody subscribes never runs at all.
Interceptors are middleware, not event listeners
Interceptors are not observers on the side. They are steps in a pipeline, and each step is responsible for continuing it. Two rules follow.
First, if you do not call next, the request never leaves. The chain stops at your function. This is sometimes intended, for example when an interceptor answers from a cache with of(new HttpResponse(...)). More often it is a bug.
import { HttpInterceptorFn } from '@angular/common/http';
// Bug: next is never called, so no request is ever sent.
export const brokenInterceptor: HttpInterceptorFn = (req, next) => {
console.log('Request to', req.url);
// missing: return next(req);
throw new Error('This interceptor must return an observable');
};The compiler catches a missing return because the function must return an Observable. Returning something else that is a valid observable, such as EMPTY, compiles fine and silently produces a request that completes with no response. Callers using subscribe with a next handler see nothing happen.
Second, whatever your function returns is what the rest of the chain, and finally the caller, receives. If you return a different observable than the one next gave you, you replace the response.
What an interceptor does not see
The interceptor chain belongs to one HttpClient. Three kinds of traffic bypass it, and they are a common source of "my interceptor is not running" reports.
- Calls that do not use
HttpClient. A directfetch('/api/data')ornew XMLHttpRequest()never enters the chain. So do requests made by third-party libraries that use their own HTTP code. Interceptors also do not apply to resources the browser loads itself, such as<img src>or<script src>. - A different
HttpClientinstance.provideHttpClient()can be called in more than one injector, for example in a lazy route'sproviders. Each call creates its own client with its own interceptor list. The parent's interceptors do not carry over, so you must register them again there. - Code that creates its own handler chain. If a service injects
HttpBackenddirectly, it talks to the backend and skips every interceptor. This is the documented way to opt a whole service out, but it also skips logging and error handling, so use it deliberately.
Why this model is useful
Seen as a pipeline, the same few ideas cover most interceptors:
- Read or replace the request before
next. Examples are adding a header or rewriting a URL. - Observe the event stream after
nextwithtap. Examples are logging or timing. - Handle errors after
nextwithcatchError. Examples are reporting or redirecting. - Skip
nextand return your own observable. Examples are caching or mocking.
The next chapters take these in turn, starting with why step 1 requires cloning the request instead of changing it.
Exercise
A service calls this.http.get('/api/items') and stores the returned observable in a variable without subscribing. A registered logging interceptor prints a line before calling next(req). Does the line print, and what happens if the service later subscribes twice?
Show answer
The line does not print when get() is called, because the observable is cold and the chain only runs on subscription. After two subscriptions the line prints twice, because each subscription runs the whole interceptor chain and sends its own request.
Exercise
Your interceptor adds a header to every request, but requests made by a third-party charting library do not carry the header. Give two reasons this can happen.
Show answer
The library may use fetch or XMLHttpRequest directly, so its requests never enter the HttpClient chain. Or it may use a different HttpClient instance, such as one provided in another injector without your interceptor registered.