Sub topic 12
Passing Metadata to Interceptors with HttpContext
This chapter assumes you have read the chapter on functional interceptors and know how to register one with withInterceptors. You should also be comfortable with TypeScript generics and the RxJS retry operator.
The problem: interceptors apply to every request
An interceptor runs for every request that passes through HttpClient. That is usually what you want, but sometimes a single call needs different treatment. A login endpoint should not get a bearer token. A health check should not trigger a global error toast. A flaky reporting endpoint might deserve extra retries.
You could encode these flags as custom headers, but headers are sent to the server. They can trigger CORS preflight requests and leak internal details. HttpContext solves this. It is a typed key-value store attached to each HttpRequest. Interceptors can read it, and it never leaves the browser.
Defining context tokens
An HttpContextToken is the key for one piece of metadata. You create it with a factory that returns the default value. The interceptor gets that default when a request does not set the token.
// http-context-tokens.ts
import { HttpContextToken } from '@angular/common/http';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
export const RETRY_COUNT = new HttpContextToken<number>(() => 0);The generic parameter fixes the value type, so context.get(RETRY_COUNT) returns a number with no casting.
Setting context on a request
Pass an HttpContext in the context option of any HttpClient method. set returns the same context, so you can chain calls.
// stats.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpContext } from '@angular/common/http';
import { Observable } from 'rxjs';
import { RETRY_COUNT, SKIP_AUTH } from './http-context-tokens';
export interface Stats {
users: number;
todos: number;
}
@Injectable({ providedIn: 'root' })
export class StatsService {
private readonly http = inject(HttpClient);
getPublicStats(): Observable<Stats> {
return this.http.get<Stats>('/api/public/stats', {
context: new HttpContext().set(SKIP_AUTH, true).set(RETRY_COUNT, 2)
});
}
}Reading context in interceptors
Each interceptor reads req.context.get(TOKEN) and changes its behavior based on the value.
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { SKIP_AUTH } from './http-context-tokens';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('access_token');
if (req.context.get(SKIP_AUTH) || !token) {
return next(req);
}
return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};// 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);
return count > 0 ? next(req).pipe(retry(count)) : next(req);
};Register both in app.config.ts with provideHttpClient(withInterceptors([authInterceptor, retryInterceptor])).
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Creating the token inside a function or component | Each call makes a new token. Lookups compare tokens by identity, so they always return the default | Define tokens once, at module level, and export them |
| Using a custom header as a flag | The flag reaches the server and may trigger a CORS preflight | Use `HttpContext` for anything only the client needs |
| Expecting `clone()` to copy the context | `clone()` keeps the same `HttpContext` instance, so a `set` in a later interceptor also changes what earlier code sees | Treat context as read-only in interceptors, or pass `clone({ context: new HttpContext() })` when you need isolation |
| Forgetting the default factory's meaning | Requests that set nothing get the default, which may switch on behavior you did not expect | Pick defaults that match the normal case, usually "off" |
Exercise
You want a global error interceptor to show a toast on every failure, except for a background polling call to /api/heartbeat. How would you implement this with HttpContext, and why is a header such as X-Silent: true a worse choice?
Show answer
Export const SILENT_ERRORS = new HttpContextToken<boolean>(() => false); at module level. In the polling call, pass { context: new HttpContext().set(SILENT_ERRORS, true) }. In the error interceptor, use next(req).pipe(catchError(err => { if (!req.context.get(SILENT_ERRORS)) { showToast(err); } return throwError(() => err); })). A header gets sent to the server, exposes internal behavior, and can force a CORS preflight. Context stays in the browser and is typed.