Sub topic 4
Writing a functional interceptor
This chapter assumes you know TypeScript, Angular services and dependency injection, basic HttpClient calls, and the RxJS basics pipe, tap and catchError. It covers the shape of a functional interceptor and the three things one can do with a request. Registration, ordering, and the auth, logging and error examples each get their own chapter, so the code here stays small.
The shape of an interceptor
A functional interceptor is a plain function of type HttpInterceptorFn. Angular calls it once for every request that goes through HttpClient. It receives two arguments and returns one value:
| Part | Type | Meaning |
|---|---|---|
| `req` | `HttpRequest<unknown>` | The outgoing request. It is immutable. |
| `next` | `HttpHandlerFn` | A function that passes a request to the next step in the chain. The last step is the backend. |
| return value | `Observable<HttpEvent<unknown>>` | The stream of events for this request, ending with the response. |
The smallest interceptor that works does nothing except hand the request along:
import { HttpInterceptorFn } from '@angular/common/http';
export const noopInterceptor: HttpInterceptorFn = (req, next) => {
return next(req);
};The parameter types come from HttpInterceptorFn, so you don't annotate them. The returned observable is what the original caller subscribes to. Whatever you return is what the caller sees.
Three things an interceptor can do
Every interceptor does some combination of three operations. Which one you choose depends on where you act relative to the call to next.
- Change the request before calling
next. You create a modified copy and pass that on. - Observe or change the result after calling
next. You pipe operators onto the observable thatnextreturns. - Skip
nextand return your own observable. The request never reaches the backend.
Changing the request
HttpRequest objects are immutable, so you can't assign to req.headers or req.url. You call req.clone() with the fields you want to change and pass the copy to next. The next chapters explain why. Here the practical rule is enough: always forward the clone, not the original.
import { HttpInterceptorFn } from '@angular/common/http';
export const clientHeaderInterceptor: HttpInterceptorFn = (req, next) => {
const modified = req.clone({
setHeaders: { 'X-Client': 'web-app' },
});
return next(modified);
};setHeaders adds or overwrites the listed headers and keeps the existing ones. clone() accepts other fields too, such as url, params, body and withCredentials. Any field you leave out is copied unchanged.
Observing the result
next(req) returns a cold observable. Nothing is sent until someone subscribes, and the original caller does that subscribing. Your interceptor attaches operators to the observable and returns the result:
import { HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const countInterceptor: HttpInterceptorFn = (req, next) => {
console.log('request started:', req.method, req.url);
return next(req).pipe(
tap({
complete: () => console.log('request finished:', req.url),
}),
);
};The first console.log runs when HttpClient calls the interceptor. Because HttpClient builds the chain lazily, that happens when the caller subscribes, not when http.get() is called. The complete callback runs after the last event has been emitted.
The stream carries more than the final response. It can emit progress events and a HttpEventType.Sent event before the HttpEventType.Response event. Code that assumes every emission is an HttpResponse will break on these events. Use event.type, or instanceof HttpResponse, to tell them apart. The logging chapter shows this in detail.
Skipping the backend
An interceptor can answer a request itself. It returns an observable of events and never calls next. A common use is a cached or stubbed response:
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
export const stubInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.endsWith('/api/ping')) {
return of(new HttpResponse({ status: 200, body: { ok: true } }));
}
return next(req);
};The return type is still Observable<HttpEvent<unknown>>, because HttpResponse is one kind of HttpEvent. Callers get the stub as if it came from a server. Interceptors later in the chain, and the backend, never see the request.
A complete runnable example
An interceptor does nothing until you register it. The next chapter covers registration properly. This minimal setup lets you try the examples above:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { clientHeaderInterceptor } from './app/client-header.interceptor';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient(withInterceptors([clientHeaderInterceptor]))],
});Then any call such as this.http.get('/api/items') in a service sends the X-Client header. Open the browser's network tab to confirm it.
Using services inside the function
Because an interceptor is a function and not a class, you can't use constructor injection. Instead, call inject() from @angular/core. Angular runs interceptors inside an injection context, so inject() works there:
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { LocaleService } from './locale.service';
export const localeInterceptor: HttpInterceptorFn = (req, next) => {
const locale = inject(LocaleService).current();
return next(req.clone({ setHeaders: { 'Accept-Language': locale } }));
};The context exists only during the synchronous part of the function call. Call inject() at the top of the function body. Don't call it inside a tap callback, a setTimeout, or after an await, because by then the context is gone and Angular throws an error saying inject() must be called from an injection context. If you need the service inside a callback, store it in a variable first:
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { tap } from 'rxjs';
import { MetricsService } from './metrics.service';
export const metricsInterceptor: HttpInterceptorFn = (req, next) => {
const metrics = inject(MetricsService);
return next(req).pipe(
tap({ complete: () => metrics.recordRequest(req.url) }),
);
};Common mistakes
- Forgetting to call
next, or forgetting to return its result. With no return, TypeScript reports a type error. If you callnext(req)in a branch and return nothing from the other branch, the request hangs or fails. Every code path must return an observable. - Calling
next(req)with the original request after you made a clone. The clone's changes are silently lost. Name the clone clearly, for exampleauthReq, and pass that name. - Trying to mutate the request.
req.headers.set(...)returns a newHttpHeadersobject and leavesrequnchanged. Using it withoutclone()does nothing. - Subscribing inside the interceptor to "trigger" the request. The caller subscribes. If you subscribe too, the request is sent twice.
- Calling
inject()late, as described above.
Choosing where to put the logic
The position of your code relative to next decides when it runs:
| Where the code sits | When it runs | Typical use |
|---|---|---|
| Before `return next(...)` | When the request is sent into the chain | Add headers, rewrite URLs, start timers |
| Inside operators on `next(...)` | When events or errors come back | Log, map responses, handle errors |
| Instead of `next(...)` | In place of the request | Cache hits, stubs, blocking a request |
Exercises
Exercise
Write an interceptor named apiPrefixInterceptor that rewrites any request whose URL starts with /api so that it starts with https://example.com/api. Other requests must pass through unchanged.
Show answer
import { HttpInterceptorFn } from '@angular/common/http';
export const apiPrefixInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.startsWith('/api')) {
return next(req.clone({ url: https://example.com${req.url} }));
}
return next(req);
};
The interceptor clones the request with a new url because requests are immutable, and it forwards the clone. Every path returns the result of next.
Exercise
An interceptor contains req.headers.set('X-Trace', '1'); return next(req);. The backend never receives the header. Why, and how do you fix it?
Show answer
HttpHeaders and HttpRequest are immutable. headers.set returns a new HttpHeaders and does not change req, and the result is discarded. Fix it by cloning: return next(req.clone({ setHeaders: { 'X-Trace': '1' } }));.
Exercise
Why does calling inject(MetricsService) inside a tap callback in an interceptor fail, and what is the fix?
Show answer
The injection context exists only while the interceptor function runs synchronously. A tap callback runs later, when events arrive, so no context is active. Call inject(MetricsService) at the top of the interceptor, store it in a constant, and use that constant inside the callback.