Sub topic 8
Example: attaching an authorization header
This chapter builds the most common interceptor in real applications. It adds a bearer token to outgoing requests. It assumes you know TypeScript, Angular services and dependency injection, and basic RxJS. It also assumes you have read the earlier chapters on HttpRequest immutability, HttpInterceptorFn, and withInterceptors. Here those pieces come together in one working example.
The problem
Many back ends expect an Authorization header on every call. A bearer token is a string that proves who the caller is, and it is sent as Authorization: Bearer <token>. Without an interceptor, each service method has to attach the header itself:
this.http.get('/api/orders', {
headers: { Authorization: `Bearer ${this.auth.getToken()}` },
});Repeating this in every call is error-prone. One forgotten call produces a 401 response that is hard to trace. An interceptor moves the logic to one place.
The token source
The interceptor needs something to ask for the token. This example uses a minimal AuthService that keeps the token in memory:
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthService {
private token: string | null = null;
setToken(token: string | null): void {
this.token = token;
}
getToken(): string | null {
return this.token;
}
}In a real application, getToken() might read from a signal, a store, or sessionStorage. The interceptor does not care. It only calls getToken().
The interceptor
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).getToken();
if (!token) {
return next(req);
}
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
});
return next(authReq);
};Walk through it in order:
inject(AuthService)runs inside the interceptor function. Angular runs interceptors in an injection context, soinject()works here. It would fail in a callback that runs later, such as inside ataphandler. Call it at the top of the function, as shown.- If there is no token, the interceptor passes the original request on unchanged. It does not block the request. A public endpoint such as a login call still works for a signed-out user.
HttpRequestobjects are immutable, so you cannot writereq.headers.set(...)and expect the request to change.req.clone()returns a new request with the changes you list.setHeadersadds or replaces the named headers and keeps all others.- The interceptor returns
next(authReq). If you forget to callnext, the request never reaches the back end and the caller's observable never emits.
`setHeaders` versus `headers`
clone accepts both setHeaders and headers. They behave differently:
| Option | Behavior | Use when |
|---|---|---|
| `setHeaders` | Sets the listed headers and keeps every other existing header. | You want to add or overwrite a few headers. |
| `headers` | Replaces the entire `HttpHeaders` object. | You want to build the full header set yourself. |
For an authorization header, setHeaders is almost always correct. Using headers by mistake can silently drop Content-Type or any header set by the caller.
Registering it
An interceptor does nothing until you register it with provideHttpClient:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { authInterceptor } from './app/auth.interceptor';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient(withInterceptors([authInterceptor]))],
});If you already registered provideHttpClient() without withInterceptors, add the feature to that same call. Registering the provider twice is a common source of "my interceptor never runs" reports.
What happens at runtime
The diagram shows one request from a service through the interceptor to the back end.
The service code stays unchanged. It calls this.http.get('/api/orders') and never mentions a token.
Limiting where the token is sent
The interceptor above attaches the token to every request that goes through HttpClient. That includes requests to other origins, such as a third-party analytics service or a public API. Sending your bearer token to those hosts leaks a credential to a party that should never see it.
Decide which URLs get the token. A simple approach compares the request URL with your API base:
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
const API_BASE = 'https://api.example.com/';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith(API_BASE)) {
return next(req);
}
const token = inject(AuthService).getToken();
if (!token) {
return next(req);
}
return next(
req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }),
);
};This checks req.url before touching the token. Two details matter:
- Relative URLs such as
/api/ordersdo not start withhttps://api.example.com/. If your app calls the API through a relative path, compare against/api/instead, or read the base from an injection token or environment file. - A prefix check is simple but not airtight. A URL like
https://api.example.com.evil.test/fails the check above only because of the trailing slash inAPI_BASE. Keep the slash, or parse the URL withnew URL(req.url)and compareoriginfor stricter matching.
Opting out for single requests
Sometimes one call to your own API must go out without a token, for example a login or a public listing endpoint. Do not add URL special cases to the interceptor for each one. A later chapter shows how an HttpContextToken lets an individual request opt out. For now, the "no token, pass through" branch already covers the signed-out case.
Common mistakes
- Mutating the request. Code like
req.headers.append('Authorization', ...)returns a newHttpHeadersand leavesrequnchanged. The header is never sent. Always useclone. - Forwarding the original request. You can build
authReqcorrectly and then writereturn next(req). The header is lost. Check which variable you pass tonext. - Reading the token too late. Calling
inject()inside an RxJS callback throws an error about the missing injection context. Read the token, or inject the service, at the top of the interceptor function. - Caching a stale token. Do not read the token once at module load and store it in a constant. Call
getToken()on each request so a refreshed or cleared token takes effect. - Expecting 401 handling. This interceptor only adds the header. It does nothing when the server rejects an expired token. A later chapter covers refreshing the token on a 401 response.
Checking it in the browser
Run the app, sign in so AuthService holds a token, and trigger any API call. Open the browser's network panel, select the request, and look at the request headers. You should see Authorization: Bearer .... Clear the token and repeat. The header should disappear while the request still succeeds or fails on its own merits.
You can also verify the behavior in a unit test with HttpTestingController. That approach is covered in the testing chapter.
Exercise
An interceptor builds const authReq = req.clone({ setHeaders: { Authorization: Bearer ${token} } }); and then ends with return next(req);. The back end reports that no Authorization header arrives. What is wrong, and how do you fix it?
Show answer
The interceptor forwards the original request instead of the clone. Because HttpRequest is immutable, clone does not change req. It returns a new object, and only that object carries the header. The fix is to return next(authReq).
Exercise
Your app calls your own API at https://api.example.com/ and also a third-party weather service. Rewrite the start of the interceptor so the token is only attached to your API. Why is checking the URL before calling getToken() a reasonable ordering?
Show answer
Add if (!req.url.startsWith('https://api.example.com/')) { return next(req); } as the first statement of the interceptor. Requests to other hosts then pass through untouched and never receive the token. Checking the URL first avoids reading the token at all for requests that will not use it, and it keeps the decision about where credentials go in one visible place.