Sub topic 8
Example: attaching an authorization header
Most APIs expect a token on every request. Adding it by hand in each service is repetitive and easy to forget. An interceptor does it once for every call. This chapter assumes you know how to write a functional interceptor, how clone() works, and how to register interceptors with withInterceptors.
The goal
Every request made through HttpClient should carry this header when the user is logged in:
Authorization: Bearer <token>If there is no token, the request should go out unchanged.
The service the interceptor depends on
The interceptor needs a place to read the token from. Here is a minimal AuthService that keeps it in memory. Your real service may read from a signal, a store, or sessionStorage.
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;
}
}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);
};Three details matter here:
inject()runs at the top of the function. An interceptor runs in an injection context, soinject()works there. Call it synchronously, not inside a callback that runs later.clone()returns a new request.HttpRequestis immutable, soreq.headers.set(...)would not change the request you forward.setHeadersinclone()adds the header and keeps any headers already present.- Both branches call
next. If the token is missing, you still forward the original request. Skippingnextwould leave the call hanging with no response.
Registering it
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]))],
});Any this.http.get('/api/orders') in the application now gets the header automatically.
Common mistakes
- Mutating instead of cloning. Changes to the original request object do not reach the forwarded one. Always forward the result of
clone(). - Sending the token to every host. This interceptor adds the header to all requests, including calls to third-party APIs. That leaks your token. Check the URL before attaching it:
const isApiCall = req.url.startsWith('/api/');
if (!token || !isApiCall) {
return next(req);
}- Injecting the service in the wrong place. Calling
inject()inside anRxJScallback fails because the injection context is gone by then. - Overwriting an existing header.
setHeadersreplaces a header with the same name. If a caller sets its ownAuthorizationon purpose, checkreq.headers.has('Authorization')first.
Public endpoints such as a login call may also need to skip the header. A later chapter shows how to opt out per request with HttpContext.
Exercise
Your app calls both /api/orders (your backend) and https://api.weather.example/forecast (a third party). The authInterceptor above adds the token to both. How would you change it so only your backend receives the token, and which line must still run for the third-party request?
Show answer
Add a check such as req.url.startsWith('/api/') and return next(req) unchanged when it is false or when there is no token. The third-party request must still go through next(req). Without that call, the request never reaches the network.