HTTP interceptors
Intercepting every outgoing request and incoming response to handle auth tokens, logging, and errors in one place.
HTTP interceptors
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An interceptor sits between every HttpClient call and the network — it sees every outgoing request and every incoming response, regardless of which service made the call.
- A functional interceptor is just a function matching `(req, next) => Observable<HttpEvent>` — it must call `next(req)` to let the request continue, or the request never actually goes anywhere.
- Interceptors run in the order they're registered, each one able to transform the request on the way out and the response on the way back — which is what makes them the right tool for auth headers and centralized logging, rather than repeating that logic in every service.
A choke point every request and response passes through
HttpClient calls happen all over a real app — a dozen different services,
each making their own requests. Plenty of concerns apply to all of them
uniformly: every request to your own API probably needs an auth token attached;
every response probably deserves the same error-handling treatment; you might
want every request and response logged the same way during development. Writing
that logic into every individual service method means writing it — and
maintaining it — a dozen times over, with every call site a chance to forget
it. An interceptor is a single choke point every request and response passes
through, regardless of which service initiated the call.
The shape of a functional interceptor
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authToken = inject(AuthService).token();
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${authToken}` },
});
return next(authReq);
};
// app.config.ts
provideHttpClient(withInterceptors([authInterceptor]));
An interceptor is a plain function: it receives the outgoing request and a
next function representing “the rest of the pipeline” (either the next
interceptor in line, or the actual network call if this is the last one).
HttpRequest objects are immutable, so attaching a header means .clone()-ing
the request with the new header set, not mutating the original — and the
interceptor must call next(authReq) with that modified request to let it
actually proceed. Skip that call, and the request simply never reaches the
network; whatever your interceptor returns instead is all the caller ever
receives.
Reacting to the response side too
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = Date.now();
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
console.log(`${req.method} ${req.url} took ${Date.now() - started}ms`);
}
}),
);
};
Interceptors aren’t limited to modifying the outgoing request — next(req)
returns an observable of the response, which you can pipe through operators the
same as any other RxJS stream (the operators lesson’s tap, catchError, and
friends all apply directly here). This is the mechanism behind centralized
request logging, and it’s the same mechanism the next lesson’s centralized
error handling builds on.
Order matters, and composability is the point
provideHttpClient(withInterceptors([authInterceptor, loggingInterceptor]));
Registered interceptors run in the order listed, each one wrapping around the
next — authInterceptor attaches its header, then hands off to
loggingInterceptor, which times the whole remaining pipeline including the
actual network call. This composability is exactly why interceptors are the
standard place for auth and logging specifically: each concern lives in its own
small, independent function, and the full pipeline is just a list naming which
ones apply and in what order, rather than every concern’s logic tangled
together inside every service that happens to make an HTTP call.
This lesson’s video builds both an auth interceptor and global error handling
directly, using the current functional interceptor API rather than the
older, deprecated class-based HttpInterceptor style — worth noting if you run
across the older pattern in an existing codebase, since the underlying concept
is identical even though the syntax has moved on.
Check yourself
Why would attaching an auth token inside an interceptor be preferable to adding an Authorization header manually inside every individual HTTP-calling service method?
An interceptor runs for every request that goes through HttpClient, automatically — write the token-attaching logic once, and it applies everywhere, with no risk of a service method forgetting to add it. Doing it manually per service method means repeating the same header-setting code dozens of times, with every single call site a chance to forget it.
Inside a functional interceptor, what happens if you never call `next(req)`?
The request never actually continues to the network — whatever observable your interceptor returns instead is all the caller ever sees. This is occasionally intentional (short-circuiting a request entirely, returning a cached response without hitting the network) but is a common accidental bug if you forget `next(req)` while writing logic that was only meant to inspect or modify the request, not replace it.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.