Sub topic 10
Cross-Cutting Concerns with Functional Interceptors
Some work has to happen on every HTTP request: attaching a token, logging timings, reacting to a 401. Writing that code into each service method spreads it thin and makes it easy to miss one call. An interceptor is a function that sits between your services and the network. It sees each outgoing request and each incoming response in one place.
This chapter assumes you have registered HttpClient with provideHttpClient, know how HttpErrorResponse and catchError work, and are comfortable with pipe and tap.
The interceptor contract
A functional interceptor has the type HttpInterceptorFn. It receives two arguments:
reqis the outgoingHttpRequest.nextis a function that passes the request to the next interceptor, or to the backend if this is the last one.
The interceptor must return the Observable that next(req) produces. It can change the request before calling next, and it can pipe operators onto the result to act on the response.
Authentication
HttpRequest objects are immutable. To add a header, you call clone and pass the copy to next.
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('access_token');
if (!token) {
return next(req);
}
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authReq);
};Logging
To observe responses, pipe onto next(req). The stream emits several event types, so filter for HttpEventType.Response.
// logging.interceptor.ts
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const started = performance.now();
return next(req).pipe(
tap(event => {
if (event.type === HttpEventType.Response) {
const ms = Math.round(performance.now() - started);
console.log(`${req.method} ${req.urlWithParams} -> ${event.status} in ${ms} ms`);
}
})
);
};Central error handling
Interceptors run in an injection context, so you can call inject() inside them. This one sends the user to the login page on a 401 and then rethrows the error so the calling service can still react to it.
// error.interceptor.ts
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
router.navigate(['/login']);
}
return throwError(() => error);
})
);
};Registering the chain
Pass the interceptors to withInterceptors. The order of the array is the order in which requests pass through them.
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
import { loggingInterceptor } from './logging.interceptor';
import { errorInterceptor } from './error.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter([]),
provideHttpClient(
withInterceptors([authInterceptor, loggingInterceptor, errorInterceptor])
)
]
};Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Changing `req.headers` directly | Headers never appear | Use `req.clone({ setHeaders })` |
| Not returning `next(req)` | The request is never sent | Always return the Observable from `next` |
| Returning `EMPTY` in `catchError` | Callers' error handlers never run | Rethrow with `throwError` |
| Class-based interceptor in `withInterceptors` | Type error at compile time | Use a function, or `withInterceptorsFromDi()` |
| Calling `inject()` inside an RxJS callback | Injection context error | Call `inject()` at the top of the function |
Exercise
With the registration order [authInterceptor, loggingInterceptor, errorInterceptor], which interceptor sees a server's 401 response first, and does the Authorization header exist when loggingInterceptor runs on the request?
Show answer
errorInterceptor sees the response first, because responses travel back through the chain in reverse order. Yes, the header exists: authInterceptor runs before loggingInterceptor and passes the cloned request that carries the Authorization header to next.
Exercise
Why does errorInterceptor call throwError(() => error) instead of returning an empty Observable after redirecting?
Show answer
Rethrowing keeps the failure visible to the service and component that made the call, so their own catchError or error callbacks still run. Returning EMPTY would complete the stream silently, and callers would never learn that the request failed.