Sub topic 15
Common pitfalls and limits
This chapter assumes you can write a functional interceptor, register it with withInterceptors, and use inject() and basic RxJS operators such as tap, catchError and retry. It collects the mistakes that cost the most debugging time, and the places where interceptors do not apply.
Forgetting to call next, or discarding the result
An interceptor must return an observable that eventually comes from next. If a code path never calls next, the request is never sent. If it returns an observable that never emits, the caller's subscription hangs without an error.
The more common slip is cloning the request and then forwarding the original:
import { HttpInterceptorFn } from '@angular/common/http';
export const brokenInterceptor: HttpInterceptorFn = (req, next) => {
req.clone({ setHeaders: { 'X-App': 'web' } }); // result thrown away
return next(req); // the original request goes out, without the header
};HttpRequest is immutable, so clone() returns a new object and leaves req unchanged. Always forward the clone:
import { HttpInterceptorFn } from '@angular/common/http';
export const fixedInterceptor: HttpInterceptorFn = (req, next) => {
const withHeader = req.clone({ setHeaders: { 'X-App': 'web' } });
return next(withHeader);
};Turn on noImplicitReturns in tsconfig.json. It catches branches that fall off the end of the function without returning.
Interceptor loops
An interceptor that makes its own HTTP call through HttpClient sends that call back through the same chain. If the nested call triggers the same condition, the interceptor calls itself again without end. The classic case is a token refresh: the interceptor sees a 401, calls /auth/refresh, and that call also returns 401 and starts another refresh.
There are two ways out. You can mark the nested request so the interceptor skips it, using an HttpContextToken. Or you can send the nested request through HttpBackend, which bypasses all interceptors.
import { HttpClient, HttpContext, HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
export const IS_AUTH_CALL = new HttpContextToken<boolean>(() => false);
@Injectable({ providedIn: 'root' })
export class TokenApi {
private http = inject(HttpClient);
refresh() {
return this.http.post<{ token: string }>(
'/auth/refresh',
{},
{ context: new HttpContext().set(IS_AUTH_CALL, true) },
);
}
}
export const guardedInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(IS_AUTH_CALL)) {
return next(req); // never re-enter refresh logic
}
// ...attach token, handle 401 by calling inject(TokenApi).refresh()
return next(req);
};The full refresh flow is covered in the previous chapter. For this chapter, remember the rule: any HttpClient call made inside an interceptor needs a guard against re-entry.
Requests that never reach your interceptors
Interceptors only see requests made through HttpClient. The following paths skip them entirely.
- Calls to
fetch()orXMLHttpRequestmade directly. - Third-party libraries that do their own networking, such as some SDKs for analytics, maps or cloud storage.
- Browser-initiated requests:
<img src>,<link>,<script>, form posts, and file downloads from<a href>. - WebSockets and server-sent events.
- Code that injects
HttpBackenddirectly.HttpBackendis the final handler at the end of the chain, so using it skips every interceptor. This is useful on purpose, and a surprise by accident.
If you need a token on an image, you have to solve it another way: a cookie, a signed URL, or fetching the bytes through HttpClient with responseType: 'blob'.
Separate HttpClient configurations do not inherit interceptors
provideHttpClient() creates a configuration for the injector where you call it. If you call it again in a child injector, such as a route's providers array, that child gets its own HttpClient with its own interceptor list. The parent's interceptors do not run for requests from services in that child, unless you add withRequestsMadeViaParent():
import { Routes } from '@angular/router';
import { provideHttpClient, withInterceptors, withRequestsMadeViaParent } from '@angular/common/http';
import { loggingInterceptor } from './logging.interceptor';
import { AdminComponent } from './admin.component';
export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [
provideHttpClient(
withRequestsMadeViaParent(),
withInterceptors([loggingInterceptor]),
),
],
},
];With this setup, the child's interceptors run first. Then the request goes to the parent's chain. Without it, the parent chain, and the auth header it adds, is silently missing. The same applies to an old HttpClientModule imported in a lazy-loaded module.
Order mistakes
Request order follows the array, and response order is reversed. Two bugs follow from that.
- A logging interceptor placed before the auth interceptor logs the request without the
Authorizationheader, because the header has not been added yet. Place it after auth if you want to see what is actually sent. Place it before if you want to see what the app asked for. - A retry placed before an interceptor that attaches a fresh token retries with the same stale token. Each retry resubscribes to everything downstream of it, so it only re-runs the interceptors that come after it in the array.
When behavior looks wrong, write the chain on paper as request → [1] → [2] → [3] → backend, then reverse it for the response.
Calling inject() at the wrong time
inject() works only in an injection context. For a functional interceptor, that is the synchronous run of the interceptor function itself. Calling it inside a tap, map or switchMap callback fails with error NG0203, because those callbacks run later.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { tap } from 'rxjs';
import { LoggerService } from './logger.service';
export const loggerInterceptor: HttpInterceptorFn = (req, next) => {
const logger = inject(LoggerService); // correct: top level of the function
return next(req).pipe(
tap(() => logger.log(req.url)), // use the captured instance
);
};Always resolve services first, then use the variable in callbacks.
Swallowed or mistyped errors
Three error-handling mistakes recur.
- Not rethrowing. A
catchErrorthat returnsEMPTYorof(null)makes the failure look like success or like an empty stream. Callers then never see their own error handler run. ReturnthrowError(() => error)unless you intend to replace the failure. - Trusting the type annotation. Writing
catchError((error: HttpErrorResponse) => ...)is only a hint. Other errors can arrive, such as an exception thrown by a downstream interceptor. Checkerror instanceof HttpErrorResponsebefore readingstatus. - Retrying unsafe requests.
retry(2)on a POST can create the same order twice if the first attempt reached the server but the response was lost. Retry only idempotent methods, and only for transient failures:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, timer } from 'rxjs';
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
return next(req).pipe(
retry({
count: 2,
delay: (error, attempt) =>
error instanceof HttpErrorResponse && (error.status === 0 || error.status >= 500)
? timer(attempt * 500)
: (() => { throw error; })(),
}),
);
};Leaking credentials to other hosts
An interceptor runs for every HttpClient call, including calls to third-party URLs. An interceptor that adds a bearer token unconditionally sends your user's token to whatever host the app contacts. Limit it to your own API:
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
const API_PREFIX = '/api/';
export const scopedAuthInterceptor: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith(API_PREFIX)) {
return next(req);
}
const token = inject(AuthService).getToken();
return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};If your API lives on another origin, compare against a configured base URL instead of a relative prefix.
Other limits worth knowing
- Events, not just one response. With
observe: 'events'or progress reporting,next(req)emits several events. Atapthat assumes one emission can run many times. Filter onevent.type. - Content-Type on FormData. Do not set
Content-Typeyourself for multipart uploads. The browser must add the boundary value, and a forced header breaks the upload. - Duplicate requests.
HttpClientobservables are cold. Each subscription sends a new request, and an interceptor that subscribes tonext(req)itself for side effects causes a second request. - Cost on every call. Interceptors run for every request. Keep them fast and avoid heavy synchronous work.
- Global tools, local needs. If only two endpoints need special handling, a per-request
HttpContextflag or a service method is clearer than a growing chain of URL checks in a global interceptor.
Quick checklist
| Symptom | Likely cause |
|---|---|
| Request never leaves, caller hangs | A path does not call `next`, or the returned observable never emits |
| Header missing on the wire | The clone was not forwarded |
| Stack overflow or endless requests | An interceptor calls `HttpClient` without a re-entry guard |
| No logs or headers for one feature area | A child `provideHttpClient` without `withRequestsMadeViaParent()` |
| NG0203 error | `inject()` called inside an RxJS callback |
| Callers never see errors | `catchError` swallows instead of rethrowing |
| Token seen by a third party | No URL scoping in the auth interceptor |
Exercise
Your app has a lazy route whose providers array contains provideHttpClient(withInterceptors([cacheInterceptor])). After this change, requests from that route stop carrying the Authorization header added by the root authInterceptor. Why does this happen, and what is the fix?
Show answer
Calling provideHttpClient in the route's injector creates a separate HttpClient configuration that replaces the parent's, so the root interceptors are not part of its chain. Add withRequestsMadeViaParent() to the route's provideHttpClient call. The route's own interceptors then run first and the request is passed on to the parent's chain, which adds the header.
Exercise
This interceptor throws NG0203 at runtime. Explain why and show the fix. export const authInterceptor: HttpInterceptorFn = (req, next) => { return next(req).pipe( tap(() => inject(LoggerService).log(req.url)), ); };
Show answer
The tap callback runs after the interceptor function has returned, when no injection context is active, so inject() fails. Move the call to the top level of the interceptor, for example const logger = inject(LoggerService);, and use logger.log(req.url) inside the tap callback.