Sub topic 12
Passing Metadata to Interceptors with HttpContext
Interceptors run for every request your application sends. That is what makes them useful, and it also causes a recurring problem: some requests need different treatment. A login call must not carry a bearer token. A health check should not show the global loading spinner. One flaky reporting endpoint should retry three times, and nothing else should retry at all.
HttpContext lets the code that sends a request attach typed, client-side metadata to it. Interceptors can then read that metadata and change how they behave. This chapter covers how the mechanism works, the patterns it supports, and the mistakes that usually come up.
This chapter assumes you have read the earlier chapters on functional interceptors and error handling. You should be comfortable writing an HttpInterceptorFn, registering it with withInterceptors, and using RxJS operators such as retry and tap.
The problem with the alternatives
Before HttpContext existed, developers used workarounds to flag special requests. Each one has a cost.
| Approach | How it works | Problem |
|---|---|---|
| Custom header such as `X-Skip-Auth` | Interceptor checks for the header, then deletes it | The flag can reach the server if the interceptor forgets to delete it, and CORS preflights may reject unknown headers |
| URL matching such as `req.url.includes('/login')` | Interceptor hard-codes a list of URLs | The list is brittle, gets out of sync with the services, and is hard to test |
| Shared service state such as `skipNextAuth = true` | The caller sets a flag before calling | Race conditions when requests overlap |
| `HttpContext` | A typed key-value store carried on the request object | Never sent to the server, typed, and scoped to one request |
HttpContext stays in the browser. Angular never serializes it into the HTTP message, so it is safe for any internal flag.
The two building blocks
The API has two classes, both exported from @angular/common/http:
HttpContextToken<T>is a key. Its constructor takes a factory function that returns the default value, and the genericTfixes the type of the value stored under it.HttpContextis the store. It maps tokens to values and hasset,get,has,deleteandkeysmethods.setreturns the context itself, so calls can be chained.
Define your tokens once, in a shared file:
// http-context-tokens.ts
import { HttpContextToken } from '@angular/common/http';
/** When true, the auth interceptor leaves the request untouched. */
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
/** How many times the retry interceptor should retry a failed request. */
export const RETRY_COUNT = new HttpContextToken<number>(() => 0);
/** Cache lifetime in milliseconds; null means "do not cache". */
export const CACHE_TTL_MS = new HttpContextToken<number | null>(() => null);The defaults matter. A request that never mentions SKIP_AUTH reads false, so authentication stays on unless a caller explicitly opts out. Choose defaults so that a forgotten flag leads to the safe behavior.
Attaching context to a request
Every HttpClient method accepts a context option. Build a fresh HttpContext, set the values you need, and pass it in:
// status.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpContext } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CACHE_TTL_MS, RETRY_COUNT, SKIP_AUTH } from './http-context-tokens';
export interface ServiceStatus {
healthy: boolean;
version: string;
}
export interface Report {
id: number;
rows: number;
}
@Injectable({ providedIn: 'root' })
export class StatusService {
private readonly http = inject(HttpClient);
/** Public endpoint: no token, cached for 30 seconds. */
getStatus(): Observable<ServiceStatus> {
return this.http.get<ServiceStatus>('/api/status', {
context: new HttpContext()
.set(SKIP_AUTH, true)
.set(CACHE_TTL_MS, 30_000)
});
}
/** Slow, flaky endpoint: retry up to three times. */
getReport(id: number): Observable<Report> {
return this.http.get<Report>(`/api/reports/${id}`, {
context: new HttpContext().set(RETRY_COUNT, 3)
});
}
}TypeScript checks the value against the token's type parameter, so .set(RETRY_COUNT, 'three') fails to compile.
Reading context in interceptors
Inside an interceptor, req.context is the HttpContext attached to the request. Calling get returns either the stored value or the token's default.
Opting out of authentication
Here is the auth interceptor from the interceptors chapter with a single guard clause added:
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { SKIP_AUTH } from './http-context-tokens';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(SKIP_AUTH)) {
return next(req);
}
const token = localStorage.getItem('access_token');
if (!token) {
return next(req);
}
return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};Per-request retry policy
// retry.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { retry } from 'rxjs';
import { RETRY_COUNT } from './http-context-tokens';
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
const count = req.context.get(RETRY_COUNT);
if (count <= 0) {
return next(req);
}
return next(req).pipe(retry({ count, delay: 500 }));
};Opt-in response caching
This example is longer. It caches GET responses only when the caller sets a TTL (time to live, meaning how long a cached response stays valid):
// cache.interceptor.ts
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of, tap } from 'rxjs';
import { CACHE_TTL_MS } from './http-context-tokens';
interface CacheEntry {
response: HttpResponse<unknown>;
expiresAt: number;
}
const cache = new Map<string, CacheEntry>();
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
const ttl = req.context.get(CACHE_TTL_MS);
if (req.method !== 'GET' || ttl === null) {
return next(req);
}
const key = req.urlWithParams;
const entry = cache.get(key);
if (entry && entry.expiresAt > Date.now()) {
return of(entry.response.clone());
}
return next(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
cache.set(key, { response: event.clone(), expiresAt: Date.now() + ttl });
}
})
);
};Register all three. The order matters, as the next section explains:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { cacheInterceptor } from './cache.interceptor';
import { retryInterceptor } from './retry.interceptor';
import { authInterceptor } from './auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([cacheInterceptor, retryInterceptor, authInterceptor]))
]
};Gotchas and failure modes
Interceptor order changes what context means
The retry operator works by resubscribing to next(req), so every interceptor after the retry interceptor runs again on each attempt. In the order above, the auth interceptor re-reads the token on every retry. That matters if a token refresh happens between attempts. Placing the cache interceptor first means a cache hit skips retry and auth entirely, which is the intended behavior. If you reverse the order, retries would bypass a cache that sits after them, and a cache placed after auth would see requests that already carry the Authorization header.
Tokens are compared by identity
A token is an object, and lookups compare object references. Two new HttpContextToken<boolean>(() => false) calls produce two unrelated keys, even though they look identical. If a service creates its own SKIP_AUTH instead of importing the shared one, the interceptor never sees the flag, and no error is reported. Keep each token in one module and import it everywhere.
Contexts are mutable and shared across clones
HttpRequest is immutable, but HttpContext is not. When an interceptor calls req.clone() without a context option, the clone holds the same HttpContext instance as the original. Any interceptor can call req.context.set(...), and later interceptors will see the change. This can be used on purpose, for example by having a logging interceptor record a start time that another interceptor reads. It also means a context shared between requests leaks state between them.
Passing `context` to `clone` replaces it
req.clone({ context: new HttpContext() }) discards every value the caller set, and later interceptors then read only defaults. To add a value without losing the others, call req.context.set(...) on the existing context instead.
Defaults are created lazily and stored
When get finds no value, it calls the token's factory and stores the result in that context. A factory like () => [] therefore gives each context its own array. After the first get, has(token) returns true, even though no caller ever set the value. Do not use has to ask "did the caller opt in?". Compare against the default instead.
Module-level state in interceptors
The cache in cacheInterceptor is a plain module variable, so the whole application shares it. In the browser that is usually fine. With server-side rendering, the cache would be shared across different users' requests on the server. For SSR, keep the cache in an injectable service that is provided per application instance, and read it with inject() inside the interceptor.
Decision guide
| You need to... | Use |
|---|---|
| Tell the server something | A header or query parameter |
| Change interceptor behavior for one call | `HttpContext` with a token |
| Change behavior for a whole group of URLs that will never vary | URL matching in the interceptor may be enough |
| Pass data from one interceptor to a later one in the same request | A context token holding a mutable value, set by the earlier interceptor |
In tests, HttpTestingController exposes the context as req.request.context. You can assert that a service set the right flags without running the interceptors.
Exercise
A teammate defines export const SKIP_AUTH = new HttpContextToken<boolean>(() => false); in auth.interceptor.ts, and someone else defines the same line again in public-api.service.ts, using the local copy when calling /api/status. Requests to /api/status still carry an Authorization header. Why, and what is the fix?
Show answer
Context tokens are looked up by object identity. The two new HttpContextToken calls create different keys, so the interceptor's req.context.get(SKIP_AUTH) never finds the value set under the service's token and falls back to the default false. Define the token once in a shared module and import that single instance in both files.
Exercise
Write a LOADING_SPINNER token and an interceptor that calls inject(LoadingService).show() before a request and hide() when it completes, errors, or is cancelled, unless the caller opted out. What default should the token have, and which RxJS operator guarantees hide() runs in all three cases?
Show answer
Use export const LOADING_SPINNER = new HttpContextToken<boolean>(() => true); so that the spinner is on by default and callers opt out with .set(LOADING_SPINNER, false). In the interceptor: if (!req.context.get(LOADING_SPINNER)) return next(req); const loading = inject(LoadingService); loading.show(); return next(req).pipe(finalize(() => loading.hide()));. finalize runs on completion, on error, and on unsubscription, so cancelled requests also hide the spinner.
Exercise
An interceptor runs const ctx = new HttpContext().set(RETRY_COUNT, 1); return next(req.clone({ context: ctx }));. A service had set SKIP_AUTH to true on that request. What does the auth interceptor, registered later, see, and how should the first interceptor be rewritten?
Show answer
The auth interceptor reads SKIP_AUTH as false, because passing context to clone replaces the whole context, and the new context only has RETRY_COUNT. The request therefore gets a token it was not meant to have. Instead, write to the existing context: req.context.set(RETRY_COUNT, 1); return next(req);. Note that this mutates a context shared with the original request.