How to use interceptors in Angular
HTTP interceptors are powerful middleware that allow you to intercept and transform HTTP requests and responses globally across your Angular application.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented interceptors in numerous enterprise Angular applications for authentication, logging, and error handling.
From my 25 years of experience in web development and 11 years with Angular, the most effective approach is to create interceptors that implement the HttpInterceptor interface and register them in your application module.
This pattern provides consistent request/response handling across all HTTP calls.
Create a class that implements HttpInterceptor interface and register it in your application providers.
import { Injectable } from '@angular/core'
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http'
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('authToken')
if (token) {
const cloned = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
})
return next.handle(cloned)
}
return next.handle(req)
}
}
// Register in app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http'
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
export class AppModule {}
The intercept method receives the original HttpRequest and a HttpHandler that represents the next interceptor in the chain. Since requests are immutable, you must clone them using req.clone() to modify headers, body, or URL. The next.handle() method passes the request to the next interceptor or the final HTTP handler. Setting multi: true allows multiple interceptors to be registered and executed in order.
This is the same interceptor pattern we use in CoreUI Angular admin templates for seamless authentication and API communication.
For response handling, you can pipe operators like tap() or catchError() to the next.handle() observable before returning it.



