Angular HTTP Interceptors

Angular HTTP Interceptors

While dealing with Authentication mechanisms and protocols in Angular, we might tend to apply some techniques which involves receiving and sending requests within our Angular application. Interceptors are one of those techniques which we can implement as an Angular service.

To give a general definition, Interceptors allow us to intercept and/or mutate incoming or outgoing HTTP Requests using the HttpClient as well as handle and return responses for a single request.

Why do we need Interceptors?

Interceptors can be beneficial when we are working with functionalities such as caching and logging. When we are dealing with a single HTTP Request or a Response, Interceptors are a done deal to work some ways pertaining to it.

I had been working on a specific login functionality where a user gets logged in after entering the username and password. It gets an access and a refresh token which get saved to local storage. In order to also ensure Auth Login service mechanism, I used an interceptor to bring out its implementation. Let us understand through the following code snippet as to how a basic interceptor is carried out. This is done in auth.interceptor.ts file:

import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Router} from '@angular/router';
import {throwError} from 'rxjs';
import {TokenService} from './token.service';
import {catchError, map} from 'rxjs/operators';
import {AuthService} from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(
    private router: Router,
    private tokenService: TokenService,
    private authService: AuthService) {
  }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(httpRequest);
}
}

To create an interceptor, we need to first implement the HttpInterceptor interface from @angular/common/http package. So whenever we are working with an HTTP Request using HttpClient service, the Interceptor gets called using the intercept() method.

A reference then gets passed through the HttpRequest object using the intercept() method. With an interceptor, we get a leverage of modifying and inspecting the request as per our necessity. We then call the next.handle and return the updated request in our Angular application.

Once when the interceptor gets created, we then need to register is as a multi-provider service since there can be multiple interceptors running within the application. We need to register it into our app.module.ts file so that it gets properly applied to our HTTP Requests. It is very important to note here that an

Interceptor will only intercept those requests that are carried out using the HttpClient service. The registered provider for our interceptor will be done as follows:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule, 
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The above is a basic implementation of how an interceptor is created and registered which is carried as a step before proceeding further into your application functionalities.

Do leave a reaction on my article if you liked and gained some insights from it!

Thank you for reading!