How to Add Header in the request in the Angular via HttpInterceptor

Every front-end application requires some kind of backend to get the data and display the same in UI and Angular which is a very popular front-end framework that also requires the backend calls to do multiple operations. In the actual real-time application we may require to edit requests like adding headers/Logs the request or response, etc...

Angular provides a feature to intercept the request/response via HttpInterceptor where we can log the request/response or add a header for all the requests going out of the front-end to the back-end.

Angular provides an interface named HttpInterceptor defined in "@angular/common/http" library of Angular in which we have an intercept method where we can intercept the request and response to customize it as per our requirement.

Suppose we want a header for every request going to the back-end and it's not feasible to do every method in Angular service which will violate code-reuse so instead we will use HttpInterceptor in Angular.

Step 1​ Create a typescript file that will inherit the intercept method of HttpInterceptor as below

import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';

/** Edit the request and pass through to the next request handler. */
@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = req.clone({
headers: req.headers.set('isProd', environment.production.toString())
});
return next.handle(authReq);
}
}


As you can see above we are adding isProd flag value to every request to determine whether this particular request is from the production environment or dev/local environment. Similarly, you can add any number of headers value in the requestor logs the request before hitting next.handle(authReq) line.

We can have multiple HttpInterceptor which can do multiple kinds of operations.

The above interceptor is only intercepting request but sometimes we may also require to intercept response as well and below is an example of the same.

intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = req.clone({
headers: req.headers.set('isProd', environment.production.toString())
});
//return next.handle(authReq);
// extend server response observable with logging
return next.handle(authReq)
.pipe(
tap((ev:HttpEvent<any>) =>{
//Success response from Interceptor
console.log(ev);
}),
catchError(response => {
if(response instanceof HttpErrorResponse){
console.log(response);
if (response.status === 401) {
//Log out the user
}
}
return throwError(response);
})
);
}


Step 2:​ Configure the HttpInterceptor providers array in AppModule class

@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule
],
exports: [RouterModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }


We can also use multiple Interceptor in a single application and the order of invocations will be the same as order it's mentioned in providers array in AppModule.


Hope you have enjoyed the article!

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee