You may ask yourself how to add Some headers for every Request that is outgoing from Angular. The most famous case is when adding some authorization, We are supposed to add a token to the backend request. The traditional way to do that is to set the Authorization Headers attribute.
But Happily, Angular Team Implements Interceptors via @angular/common/http which helped in setting the needed Headers attribute just once.
![How to add Angular Interceptor. Set Headers for every Request.](https://webdevtutos.com/wp-content/uploads/2023/10/How-to-add-Angular-Interceptor.-Set-Headers-for-every-Request.-2048x1152-1-1024x576.webp)
What is Angular Interceptor?
Interceptor, as its name invoke, is a built-in Interface that we can get implemented using Angular HTTP Module.
For every outgoing HTTP request, the angular Interceptor will catch the request, and We can in that way change the Headers, the Body, or whatever we want.
Let’s see how we can generate an Angular Interceptor
How to generate an Angular Interceptor?
We can easily add Http Interceptor Through the Angular CLI command. You just need to type the following command.
//syntax
ng generate interceptor <<class Name>>
//Example
ng generate interceptor auth
and an AuthIntercptor service will be created containing this code.
//auth.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request);
}
}
As You see the intercept method will intercept every HTTP request made by Angular.
The common use case that forces us to use interceptors is adding Token to the Authorization Header.
Let’s see an example with JWT Authtentication
//auth.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
token: string = localStorage.getItem("Token");
constructor() {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request);
}
addAuthenticationToken(request: HttpRequest<any>) {
return request.clone({
setHeaders: {
Authorization: `Basic ${this.token}`
}
})
}
}
Conclusion
In this blog post, we learned how to Set Headers for every Angular Request by generating Angular Interceptors.
Stay Tuned and give a look at our blog.