Use HTTP Interceptor to Set Auth Header for API Requests with Angular

    Nov 16, 2021       by Pankaj Kumar
use-http-interceptor-to-set-auth-header-for-api-requests-with-angular.jpg

Interceptors provide a way to intercept the incoming and outgoing HTTP requests using HttpClient. By using Interceptors we can easily modify/change the header, body of the request which will apply to all requests from the single file of code. It is also helpful if its needed to format the response from the HTTP request.

 

Common Use Cases of Interceptors

  • Add an auth token(for authenticated requests) or some custom HTTP header for all outgoing HTTP requests.
  • Catch HTTP responses to do custom formatting before transferring the data to the service/component.
  • print all HTTP requests in the console using console.log.

 

Let's understand more using the below example:

In the below example, I am going to use the interceptor to set JWT token to the HTTP request for all the HTTP requests after login, and also base url will be set from this file which will effect all the HTTP requests.

Use of Interceptor is very common in Angular, But we can also use Interceptor with React to set Auth header with API request and other javascript libraries.

Let's have a look at the code inside the interceptor file(interceptor.service.ts)

 

 
import {
    HttpInterceptor,
    HttpRequest,
    HttpHandler,
    HttpEvent
  } from "@angular/common/http";
  import { Observable } from "rxjs";
  import { Injectable } from "@angular/core";
 
  import { environment } from '../../environments/environment';
 
  @Injectable()
  export class InterceptorService implements HttpInterceptor {
   
    intercept(
      req: HttpRequest<any>,
      next: HttpHandler
    ): Observable<HttpEvent<any>> {
        const token =  localStorage.getItem("currentUser") && localStorage.getItem("currentUser")!=null ? localStorage.getItem("currentUser") :'';
        req = req.clone({
        headers: req.headers.set(
            "x-access-token",
            token  
        ),
        url: environment.apiBaseUrl + req.url
        });
     
      return next.handle(req);
    }
  }
 

 

In the above file, I have imported HttpInterceptor from HTTP Client Module and base url from the environment file. Every time our application make the HTTP request using HttpClient, the interceptor calls the intercept() method. Angular passes the reference to the httpRequest object when the intercept() is called. We can inspect and modify as per the requirement. Once logic is complete, next.handle() is called and returned the request to the application. 

At below part of the code token and base url has been set which will effect for all the HTTP request.

 

Register Interceptor service into App module

 

 
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
 
import { NgxSpinnerModule } from "ngx-bootstrap-spinner";
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// Interceptor
import { InterceptorService } from './_interceptor/interceptor.service';
 
// Modules
import { CoreModule } from './core/core.module';
 
// Service
import { RoutingService } from './_services/routing.service';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
// import { LayoutService } from './_services/layout.service';
import { NotifierModule, NotifierOptions } from 'angular-notifier';


 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    CoreModule,
    HttpClientModule,
    NgxSpinnerModule,
    NoopAnimationsModule,
  ],
  providers: [
    RoutingService,
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true }
  ],
  schemas :[ CUSTOM_ELEMENTS_SCHEMA ],
  bootstrap: [AppComponent]
})
export class AppModule { }
 

 

It is necessary to register it as a multi-provider since there can be multiple interceptors running within an application, So add the service in the providers array as mentioned above.

 

Note: Interceptors only intercept requests that are made using the HttpClient service.

Conclusion

Interceptor helps us to add/update the HTTP requests by intercepting them while making the HTTP requests. It is very useful while working on huge apps and when there is a need to add custom headers to the outgoing request, log the incoming response, etc.

For a developer, It is highly recommended to use Interceptor in the project. Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.


Find other similar Articles here: