Sub topic 11
Controlling interceptors per request with HttpContext
This chapter assumes you can write a functional interceptor, register it with withInterceptors, and read a request from inside it. You should also be comfortable with inject() and req.clone().
The problem: one interceptor, a few exceptions
An auth interceptor runs on every request. Some requests should not carry a token, such as a public endpoint or a call to a third-party API. You have three poor options:
- Match URLs inside the interceptor. This is brittle and couples the interceptor to your routes.
- Add a custom header such as
X-Skip-Auth. The header is sent over the network unless you remove it, and it is visible to the server. - Write a second
HttpClientsetup. This duplicates configuration.
HttpContext solves this. It is a typed key-value store attached to a request. It travels with the request through the interceptor chain and is never sent to the server.
How HttpContext works
Two classes are involved:
HttpContextToken<T>is a typed key. You create it once and give it a default value through a factory function.HttpContextis the store. You set values on it withset(token, value)and read them withget(token).
If a request does not set a token, get returns the token's default. That means interceptors can read the token without checking whether anyone set it.
Step 1: define the token
Declare the token in a shared file, next to the interceptor that reads it.
import { HttpContextToken } from '@angular/common/http';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);The default is false, so every request is authenticated unless it opts out.
Step 2: read it in the interceptor
import { 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);
};The interceptor still calls next on the skip path. Forgetting that call would stop the request entirely.
Step 3: set it at the call site
import { HttpClient, HttpContext } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { SKIP_AUTH } from './auth.interceptor';
@Injectable({ providedIn: 'root' })
export class PublicApi {
private http = inject(HttpClient);
getAnnouncements() {
return this.http.get('/api/public', {
context: new HttpContext().set(SKIP_AUTH, true),
});
}
}set returns the same HttpContext, so you can chain several tokens.
Common errors
- Creating the token twice. Tokens are matched by identity, not by name. If two files each call
new HttpContextToken(...), they are different keys. Export one instance and import it everywhere. - Expecting a token to survive a manual new request.
req.clone()keeps the context. Building a freshHttpRequestdoes not, unless you pass it. - Using the context for data the server needs. The context stays on the client. Use headers or parameters for anything the backend must see.
- Using a non-boolean default carelessly. Tokens can hold any type, such as a retry count. Choose a default that gives the right behavior when nothing is set.
Exercise
Exercise
You add an interceptor that retries failed requests. Some POST requests must never be retried. Using HttpContext, how would you let a single call opt out, and what default should the token have?
Show answer
Export a token such as NO_RETRY = new HttpContextToken<boolean>(() => false). In the interceptor, check req.context.get(NO_RETRY) and return next(req) without the retry operator when it is true. At the call site, pass context: new HttpContext().set(NO_RETRY, true). The default is false so that requests retry unless they opt out.