Sub topic 11
Controlling interceptors per request with HttpContext
This chapter assumes you can write and register a functional interceptor, you know that HttpRequest is immutable and must be cloned, and you are comfortable with inject() inside an interceptor. It covers how to change an interceptor's behavior for a single request without touching the URL or adding fake headers.
The problem: one interceptor, many exceptions
An interceptor runs for every request that goes through HttpClient. That is the point of it, but some requests need different treatment:
- A call to a public endpoint should not carry an
Authorizationheader. - A background polling call should not show a global loading spinner.
- A request to a third-party API should not be logged or retried.
Developers often work around this in ways that cause trouble later.
| Workaround | Why it causes trouble |
|---|---|
| Check the URL inside the interceptor (`req.url.includes('/public')`) | Couples the interceptor to URL layout. A renamed route silently breaks it. |
| Add a custom header such as `X-Skip-Auth` | The header is a real HTTP header, so it is sent to the server unless you also remember to remove it. |
| Register a second `HttpClient` with a different interceptor list | Duplicates configuration and is hard to keep consistent. |
HttpContext solves this by attaching typed metadata to a request. The metadata travels with the request through the interceptor chain and is never sent over the network.
How HttpContext works
Three pieces work together.
HttpContextToken<T>is a typed key. You create it once, usually in the same file as the interceptor that reads it. Its constructor takes a function that returns the default value.HttpContextis a map from tokens to values. EveryHttpRequesthas acontextproperty.- The caller sets values with
context.set(token, value). The interceptor reads them withreq.context.get(token).
If the caller does not set a token, get returns the default from the token's factory. That is why a token such as SKIP_AUTH defaults to false: requests that say nothing get the normal behavior.
Declaring a token
Declare the token as an exported constant so that both the interceptor and the callers can import it.
import { HttpContextToken } from '@angular/common/http';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);The type parameter describes the value. The factory function supplies the default. Using a factory instead of a plain value lets you return a fresh object each time when the value is mutable, for example an array.
Do not create a second HttpContextToken with the same name in another file. Tokens are compared by object identity, not by a string name, so two tokens that look alike are different keys.
Reading the token in the interceptor
This is the auth interceptor from the earlier chapter, extended with an opt-out.
import { HttpContext, HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
export const authInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(SKIP_AUTH)) {
return next(req);
}
const token = inject(AuthService).getToken();
return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};
// In a service:
// this.http.get('/api/public', { context: new HttpContext().set(SKIP_AUTH, true) });Two details are worth noticing.
- The check happens before
inject(AuthService). When the flag is set, the interceptor does no extra work. - In the skip branch the interceptor still calls
next(req). Skipping your logic never means skippingnext. If you return without calling it, the request is never sent.
Setting the token at the call site
HttpClient methods accept a context option. HttpContext.set returns the same context, so calls chain.
import { HttpClient, HttpContext } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { SKIP_AUTH } from './auth.interceptor';
@Injectable({ providedIn: 'root' })
export class PublicApi {
private readonly http = inject(HttpClient);
getAnnouncements() {
return this.http.get<string[]>('/api/public/announcements', {
context: new HttpContext().set(SKIP_AUTH, true),
});
}
}The caller states its intent in code that the compiler checks. If you pass a string where the token expects a boolean, TypeScript reports an error.
Tokens that carry more than a flag
A token's type can be any type. A few useful patterns:
- A number, such as a retry count:
new HttpContextToken<number>(() => 3). - A string union, such as a loading indicator mode:
'global' | 'none'. - An object with several options.
Here is a retry interceptor whose attempt count is controlled per request.
import { HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
import { retry } from 'rxjs';
export const MAX_RETRIES = new HttpContextToken<number>(() => 2);
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
const attempts = req.context.get(MAX_RETRIES);
return attempts > 0 ? next(req).pipe(retry(attempts)) : next(req);
};A caller that must not repeat a non-idempotent request, such as a payment, sets MAX_RETRIES to 0:
import { HttpClient, HttpContext } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { MAX_RETRIES } from './retry.interceptor';
@Injectable({ providedIn: 'root' })
export class PaymentApi {
private readonly http = inject(HttpClient);
pay(order: { id: string; amount: number }) {
return this.http.post('/api/pay', order, {
context: new HttpContext().set(MAX_RETRIES, 0),
});
}
}Context survives cloning
When an interceptor calls req.clone(...), the clone keeps the same context object. So a token set by the caller is still visible to every interceptor later in the chain, even if earlier interceptors cloned the request to add headers.
This also means an interceptor can write to the context to pass information downstream:
import { HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
export const REQUEST_STARTED_AT = new HttpContextToken<number>(() => 0);
export const stampInterceptor: HttpInterceptorFn = (req, next) => {
req.context.set(REQUEST_STARTED_AT, Date.now());
return next(req);
};An interceptor registered after stampInterceptor can read REQUEST_STARTED_AT. Use this sparingly. Writing to a shared object is a side effect, and it makes the order of interceptors matter in a way that is easy to forget. If the information can be computed locally, compute it locally.
Edge cases and gotchas
- The default applies when nothing is set. If you change a default from
falsetotrue, every existing call changes behavior. Prefer defaults that match the common case. - Context is per request. A context object you build once and reuse across calls is shared by those calls. If an interceptor writes to it, later requests see the change. Create a new
HttpContextfor each call unless sharing is intended. - Retries and resubscription. The observable returned by
HttpClientis cold. Each subscription sends a new request, but it reuses the sameHttpRequestand so the same context. A value written to the context during the first attempt is still there on the second. - Not sent to the server. The context is never serialized. If the backend must know something, use a header or a body field instead.
- Only for
HttpClient. Requests made withfetchorXMLHttpRequestdirectly never pass through interceptors, so there is no context to read. - Tokens are public API. Once other teams import
SKIP_AUTH, renaming or retyping it is a breaking change. Keep the set of tokens small and document what each one does.
Testing the opt-out
You can test both paths with HttpTestingController, the same way as the header test from the testing chapter.
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpContext, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { SKIP_AUTH, authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
describe('authInterceptor with SKIP_AUTH', () => {
let http: HttpClient;
let controller: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
{ provide: AuthService, useValue: { getToken: () => 'abc' } },
],
});
http = TestBed.inject(HttpClient);
controller = TestBed.inject(HttpTestingController);
});
it('adds the header by default', () => {
http.get('/api/data').subscribe();
const req = controller.expectOne('/api/data');
expect(req.request.headers.get('Authorization')).toBe('Bearer abc');
req.flush({});
});
it('omits the header when SKIP_AUTH is true', () => {
http.get('/api/public', { context: new HttpContext().set(SKIP_AUTH, true) }).subscribe();
const req = controller.expectOne('/api/public');
expect(req.request.headers.has('Authorization')).toBe(false);
req.flush({});
});
afterEach(() => controller.verify());
});Choosing between context, headers, and URLs
| Need | Best tool |
|---|---|
| Change client-side interceptor behavior for one call | `HttpContext` |
| Tell the server something about the request | An HTTP header or body field |
| Apply different behavior to a whole API area, such as all calls to one host | A URL check in the interceptor, ideally against a configured base URL |
| Different behavior for a whole feature with its own interceptor list | A separate provider setup, used rarely |
Use HttpContext when the decision belongs to the code making the call. Use a URL check when the decision belongs to the destination.
Exercise
You add export const SHOW_SPINNER = new HttpContextToken<boolean>(() => true); and a loading interceptor that shows a spinner only when req.context.get(SHOW_SPINNER) is true. A polling service must not show the spinner. Write the call that sets this up, and explain what happens to other callers that set nothing.
Show answer
The polling call passes { context: new HttpContext().set(SHOW_SPINNER, false) } as its options, for example this.http.get('/api/status', { context: new HttpContext().set(SHOW_SPINNER, false) }). Callers that set nothing get the default from the token's factory, which is true, so they still show the spinner. The context is never sent to the server, and it stays on the request when other interceptors clone it.
Exercise
An interceptor skips its work when a token is set, and its author writes if (req.context.get(SKIP_AUTH)) { return; }. What goes wrong, and what is the fix?
Show answer
The interceptor returns undefined instead of an observable and never calls next, so the request is not sent and the caller's subscription fails or hangs. The fix is return next(req); in the skip branch. Skipping your own logic still requires passing the request along the chain.