HTTP Interceptors
11 min read
What Are HTTP Interceptors?
An interceptor is a function (or class) that sits in the HTTP pipeline and can inspect or transform every outgoing request and every incoming response. Common uses include attaching auth tokens, adding global error handling, showing a loading spinner, and logging.
Functional Interceptors (Angular 15+)
ts
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
const token = auth.getToken();
if (!token) return next(req);
const cloned = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(cloned);
};ts
// error.interceptor.ts
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((err: HttpErrorResponse) => {
if (err.status === 401) {
router.navigate(['/login']);
}
if (err.status === 403) {
router.navigate(['/forbidden']);
}
return throwError(() => err);
})
);
};Registering Interceptors
ts
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { authInterceptor } from './interceptors/auth.interceptor';
import { errorInterceptor } from './interceptors/error.interceptor';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withInterceptors([authInterceptor, errorInterceptor])
)
]
});Interceptors run in the order they are listed in withInterceptors([...]). The request goes through them in order (first to last) and the response comes back in reverse order (last to first). Keep this in mind when ordering auth and logging interceptors.
Requests are immutable — you cannot mutate req directly. Always use req.clone({ ... }) to create a modified copy. This keeps the pipeline predictable and prevents hard-to-debug side effects.
Ready to test yourself?
Practice Angular— quiz & coding exercises