Sub topic 6
How interceptor order affects requests and responses
This chapter assumes you can write a functional interceptor with HttpInterceptorFn and register it with provideHttpClient(withInterceptors([...])). It also assumes you know basic RxJS: pipe, tap, and catchError. Here you will learn which interceptor sees a request first, which sees the response first, and how to use that when you place your own interceptors.
The rule: in on the way out, reverse on the way back
Interceptors run in the order of the array you give to withInterceptors. A request passes through the first interceptor, then the second, and so on, until the last one hands it to the backend. The response then travels back through the same interceptors in reverse order.
This is a stack, like layers of an onion. The first interceptor in the array is the outermost layer. It sees the request before any other interceptor does and sees the response after every other interceptor has finished with it.
Seeing the order for yourself
The following tracing helper logs when a request leaves an interceptor and when a response arrives back at it. It works on the HttpEvent stream that next returns, so it checks for the Response event type.
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export function trace(name: string): HttpInterceptorFn {
return (req, next) => {
console.log(`${name}: request`);
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
console.log(`${name}: response`);
}
}),
);
};
}Register three of them:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { trace } from './app/trace.interceptor';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(withInterceptors([trace('A'), trace('B'), trace('C')])),
],
});One GET request prints this:
A: request
B: request
C: request
C: response
B: response
A: responseThe request lines follow array order. The response lines follow the reverse order. Everything below is a consequence of this one pattern.
What each interceptor sees depends on its position
Each interceptor receives the request as the interceptors before it left it. Because HttpRequest is immutable, every clone() produces a new object that is passed down the chain. An interceptor only sees the changes made by interceptors earlier in the array.
Consider the registration from the earlier chapters:
provideHttpClient(withInterceptors([authInterceptor, loggingInterceptor]));authInterceptor runs first and clones the request with an Authorization header. loggingInterceptor runs second, so its req already carries that header. If you swap the two, the logger sees the original request without the header.
This matters in two ways:
- A logger that prints
req.headerswill print the bearer token if it is placed after the auth interceptor. Put the logger first, or never log theAuthorizationheader. - A logger placed first measures elapsed time including the work of every interceptor after it. A logger placed last measures time closer to the network call itself.
A common layout puts the interceptors in this order, from outermost to innermost:
| Position | Typical interceptor | Reason |
|---|---|---|
| First | Logging or timing | Sees the original request and the final result, and times the whole chain |
| Middle | Authentication, other header changes | Modifies the request before it is sent, and sees raw responses |
| Last | Retry or low-level error mapping | Sits closest to the network and sees raw failures first |
This is a starting point, not a rule. The right order depends on what each interceptor must see.
Errors travel back through the chain too
An error from the backend arrives in the observable returned by next. It moves outward through the interceptors in reverse order, and each interceptor can handle it, transform it, or rethrow it.
Take the error interceptor from the earlier chapter:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 0) {
console.error('Network error', error.error);
} else {
console.error(`Server returned ${error.status}`, error.message);
}
return throwError(() => error);
}),
);
};If it is first in the array, it sees an error only after every later interceptor has had its chance to handle it. If it is last, it sees the raw error before anything else does. If an interceptor between them swallows the error with catchError and returns a fallback value, an outer error interceptor never sees a failure at all.
Order and retry
Order changes behavior most clearly with retry. The RxJS retry operator resubscribes to the observable it wraps. In an interceptor, that observable is next(req), so a retry reruns every interceptor after it in the chain. It does not rerun the ones before it.
import { HttpInterceptorFn } from '@angular/common/http';
import { retry } from 'rxjs';
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
return next(req).pipe(retry({ count: 2 }));
};The GET check is deliberate. Retrying a POST can create duplicate records, so this example retries only requests that are safe to repeat.
Now compare two registrations:
// Retry is inner: each retry goes through the auth interceptor again.
provideHttpClient(withInterceptors([loggingInterceptor, authInterceptor, retryInterceptor]));
// Retry is outer: auth runs once, and retries reuse the same cloned request.
provideHttpClient(withInterceptors([loggingInterceptor, retryInterceptor, authInterceptor]));In the first registration, retry sits after auth. authInterceptor ran only once, so every retry sends the same Authorization header. In the second registration, retry sits before auth. Each attempt passes through authInterceptor again, so it can read a fresh token every time. Which one you want depends on whether the interceptors after the retry can produce different results on a second pass.
The same logic applies to logging. A logger placed before the retry interceptor logs one request and one final result. A logger placed after it logs every attempt.
Short-circuiting: stopping the chain early
An interceptor does not have to call next. If it returns its own observable of events, the interceptors after it never run, and no network request is made. The response still travels back through the interceptors before it.
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of, tap } from 'rxjs';
const cache = new Map<string, HttpResponse<unknown>>();
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
const cached = cache.get(req.urlWithParams);
if (cached) {
return of(cached);
}
return next(req).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
cache.set(req.urlWithParams, event);
}
}),
);
};Position decides what the cache hides. If cacheInterceptor is before authInterceptor, a cached hit skips authentication entirely, which saves work but also serves a cached response to a user whose token has since expired. If it is after, auth runs on every call and only the network trip is skipped. If it is before loggingInterceptor, cached hits never appear in the logs.
Mixing functional and class-based interceptors
Interceptors registered through the HTTP_INTERCEPTORS token run as a group, and withInterceptorsFromDi() decides where that group sits. It takes its place among the other features of provideHttpClient, in the order you list them:
provideHttpClient(
withInterceptors([loggingInterceptor]),
withInterceptorsFromDi(), // DI-based interceptors run after loggingInterceptor
);Inside the DI group, order follows the order of the multi: true providers. If you are migrating, move interceptors one at a time and re-check the trace output, because a changed position can change behavior.
Checklist for choosing a position
- Does the interceptor need to see headers added by another one? Put it after that one.
- Should it observe the original, unmodified request? Put it before the modifying interceptors.
- Should it see the final result after other interceptors handle errors? Put it earlier in the array.
- Should it see raw network failures? Put it later in the array.
- Does it retry or short-circuit? Decide which interceptors should rerun or be skipped.
Exercise
You register withInterceptors([trace('A'), cacheInterceptor, trace('B')]). A GET request is made twice to the same URL. On the second call the cache holds a response. What does the console print for the second call?
Show answer
Only "A: request" and then "A: response". The cache interceptor returns of(cached) without calling next, so trace('B') never runs. The cached HttpResponse still flows back to A, so A logs its response line.
Exercise
You need an interceptor that adds a fresh token on every retry attempt. Should retryInterceptor be placed before or after authInterceptor in the array, and why?
Show answer
Before it. retry resubscribes to next(req), which reruns only the interceptors after the retry interceptor. With retryInterceptor first and authInterceptor after it, each attempt passes through authInterceptor again and can read a new token.