How to Create and Use HTTP Interceptor in Angular 14

Step-by-step guide on getting started HTTP Interceptor in Angular.learn how to leverage them to enhance handling authentication, error handling, caching, and modify HTTP requests and responses.
by

Prerequisites

Before starting an Angular project, you should have the following prerequisites installed on your system

  1. Node.js
  2. npm (Node Package Manager)
  3. Angular CLI

Once you have installed these prerequisites, you are ready to create your first Angular application.

What Is An Angular HTTP Interceptor

In Angular, an HTTP interceptor is a build in feture of the Angular framework that allows us to intercept HTTP requests and responses before they are sent to or received from the server. Interceptor provide a way to modify the request and response , such as adding authentication JWT tokens in HTTP request headers, modifying the request body or error handling .

The HttpInterceptor is a interface, which requires the implementation of a intercept method. This method takes an HttpRequest object and an HttpHandler object as arguments and returns an Observable<HttpEvent>.

Can We use multiple Interceptors?

Yes, you can use multiple interceptors in Angular. In fact, interceptors are designed to be chained together to perform a series of tasks before the request is sent or after the response is received.

When more than one interceptor are used, the interceptors execute in a chain and and each interceptor can modify the request or response. The chain's interceptor placement is important since it affects the order in which they will be performed.

app.component.tsts
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorA, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true }
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true }
  ]
})
export class AppModule { }

How to create a simple HTTP Interceptor?

The steps below describe how to create an HTTP interceptor in Angular.

  1. Using the CLI command, create a new Angular service:
app.component.tsts
ng generate service http-interceptor 
//or we can use sort command
ng g s http-interceptor
  1. Implement the HttpInterceptor interface in your service class. Export the @Injectable() decorator after adding it to your class.
app.component.tsts
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  constructor() { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //add your interceptor logic here
    return next.handle(request);
  }
}
  1. Finally, include the interceptor in your AppModule providers array.

How to use the interceptor?

app.component.tsts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from './http-interceptor.service';

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

For example, if you have two interceptors, LoadingInterceptor and ErrorsInterceptor, and you want LoadingInterceptor to run before ErrorsInterceptor, you would specify them in the providers array using the following syntax:

app.component.tsts
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorA, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true }
  ]
})
export class AppModule { }

How To Catch HTTP Error in Angular

When it comes to error handling, one common use case for interceptors is to handle errors that occur during HTTP requests. you can use HttpHandler object to intercept all HTTP responses and check for errors. If an error is detected, we can perform appropriate action.

The HTTP errors fall into two categories. The client side error and server side error.

  1. Client Side Error : may be due to a network error or an error while executing the HTTP request.
  2. Server Side Error : when the request fails due to any reason.
app.component.tsts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler } from '@angular/common/http';
import {  HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof ErrorEvent) {
            console.log('this is client side error');
            console.log(`Error: ${error.error.message}`);
          }
          else {
             console.log('this is server side error');
             console.log(`Error Code: ${error.status},  Message: ${error.message}`);
             if (err.status === 401) {
                // refresh JWT token 
                // or redirect to login page
                // or display error message
                console.log('Unauthorized');
             }
            else if(err.status === 400){
                // not found error 
            }
          }
        return throwError(error);
      })
    );
  }
}

How To Set Authentication Token

app.component.tsts
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  constructor() { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // get jwtToken
    const jwtToken = localStorage.getItem('jwtToken');
    // Add the authentication token to the request headers
    if (jwtToken) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${jwtToken}`
        }
      });
    }
    return next.handle(request);
  }
}

How To Show The Loading Screen

app.component.tsts
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  constructor() { }
  
    return next.handle(request);
  
}

How To Modify HTTP request headers

How To Modify The Request Body

How To Change The Requested URL

Conclusion

Thank you for reading this article. Hopefully now you know How to Create and Use HTTP Interceptor in Angular 14.