HomeBlogWeb DevelopmentHow to Use HTTP Interceptor in Angular?

How to Use HTTP Interceptor in Angular?

Published
25th May, 2024
Views
view count loader
Read it in
6 Mins
In this article
    How to Use HTTP Interceptor in Angular?

    An application is incomplete without the backend server that displays data on UI. Various backend servers are available on the internet. Most application uses JSON and XML servers to perform their tasks. The API is used for the backend communication between components and methods. This communication is based on two significant concepts: authorization and authentication. 

    Interceptors are another significant part of Angular programming. They are used to modify the HTTP requests by adding several functionalities. Authentication determines the security level of an application. The authentication check is placed on the user’s identity to make a good connection. 

    In contrast to this, authorization is a concept used to determine a user's authority. Interceptor in angular is a great way to modify your code and make it more readable. Also, they are used in various other fields, which we will discuss later.

    For more information, check out the AngularJS certification course and become an advanced angular developer in no time. 

    What is an Angular HTTP Interceptor?

    Angular HTTP Interceptor
    JavaScript in Plain EnglishThe angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators. 

    The interceptors do not initiate the handle method and handle the requests at their level. The interceptor is used to perform various functions and methods to perform specific tasks. We would highly recommend you to refer to the best Web Development course online course and get your hands on angular. 

    How Does the Interceptor Work?

    Interceptors in Angular operate much like security guards overseeing the communication highway between your application and the server. To grasp their functionality, let's look at these real-life examples in the context of how to use interceptor in Angular:

    So, I was mailing a package with the help of a courier company. When I inquired about the entire workflow of sending the parcel to the destination, the courier company replied that before it reaches its destination, the courier service takes the package, attaches a tracking label to it (similar to modifying the HTTP headers), and ensures that it meets the shipping regulations. Therefore, this interception thus guarantees a secure and traceable journey for the package, much like how interceptors secure and modify requests before reaching their server destination. 

    Now, let us consider a scenario where you are receiving a package. Before it reaches your hands, a vigilant quality control inspector will examine the contents of the package and make sure that everything aligns with your expectations. In the digital world, an interceptor can similarly check and modify the incoming data, ensuring that it meets the predefined criteria. 

    So, in everyday terms, an angular interceptor acts like a guardian for our application's communication system, by adding an extra layer of security and customization. They interfere in the exchange of information dynamically, similar to how different packages are handled in the real world, giving developers a valuable tool for customizing and securing their applications. 

    How to Create HTTP Interceptor?

    Before implementing an angular interceptor, you must create one. So, here we will help you create a service that will implement the HTTP interceptor angular interface. Here are the code snippets and examples to create an interceptor of your own.

    • First, create an injectable service. 

    • Now, implement the intercept method within the above class. 

    • Then add the class within the root module. Use the token named HTTP_INTERCEPTOR. 

    10 Ways to Use Interceptors in Angular

    There are various ways to use the angular HTTP interceptor. We have selected the top 10 most straightforward ways to use the angular HTTP interceptor. We will study them with relevant codes and examples. 

    1. Loaders: Interceptors can be used as loaders whenever there exist different active requests. A loader function with both, hide and show features is used to handle the requests. 

    2. URL: Changing the URLs is what the interceptor angular is capable of. You can change the URL, and the interceptor will behave like an API interceptor used to add prefixes.

    3. Headers: Angular interceptors manipulate the headers as they provide features such as authentication and authorization. The angular HTTP interceptors are used to protect the application against XSRF.

    4. Converting: Interceptor can even convert the format of an API that we receive. A more likely example is to convert the XML file to a JSON file.

    5. Errors: Interceptors are used in two ways to detect the errors- retry the HTTP call, and the second one is to keep a check on the status of the exception that occurred.

    There are various HTTP error codes such as error codes 400, 500, and 200 and their series, which are to be handled individually. The error code 500 determines that the API has not received the request. The error code 401 means that the access token is no longer active.

    6. Notifications: Interceptors can even show various messages as notifications. In the below example, we have printed an “object created” message on the console. The notifications can also be displayed whenever we detect an error.

    7. Fake backend: As the name suggests, the fake backend is used to develop the application when the backend doesn’t exist. The response is based on the request, after which we return an observable object of the HTTP request. 

    The code snippet is attached below- 

    8. Profiling: Interceptors have the ability to both requests and respond simultaneously. They can even log the HTTP operation without any time delay. So, it becomes easy to note the time of both the request and the response and can be consoled together.

    Different profiles can be logged into the database to get the information. 

    9. Authentication: Authentication is the basic functionality added to any application to check the user’s authentication. This is a common and basic use of the interceptors to make a check-in at the application’s usage. It connects various parameters such as the refresh tokens, adds bearer tokens, and redirects to the login URL. 

    10. Catching: Interceptors are capable enough to detect any errors as it handles the requests besides forwarding them to the handle method. We will use a key-value map where the key will be more like a URL. The observable response can be returned directly to the handle function as soon as we find any relevant response on the map.

    This is feasible as it saves a lot of time and energy. The developers do not always need to search everything in the backend when they have already caught one. 

    Here’s the code for this technique. 

    Create the Interceptor

    To create an interceptor angular, create a file named AppHTTPInterceptor.ts within the src-app folder. Refer to the below code or place it just the same way. 

    The code involves the following steps-

    • Import all the essential modules required by the application, such as the observable, injectable, HTTP requests, HTTP handler, HTTP events, etc. 
    • Now, create a class implementing the HTTP interceptor in angular interface.
    • Later, you need to create one interceptor method with two arguments. The arguments would be the HTTP request and the HTTP handler. 
    • In the method's body, you can change the code at your convenience. After making the changes, just call the handle method of the HTTP handle using the HTTP request object. The handle method initiates the upcoming interceptor or sends the HTTP request straightaway to the server. 

    Setting the New Headers

    We have already consoled the request. This section will add HTTP and custom headers to the request. So, let us learn how to do it,

    1. Add the content-type: Modifying request needs a clone of the request on which we will be performing the task, the request. The clone method helps us to modify the request and its properties. The header object is immutable, so we need to clone the request. RequestAppendAppend is an alternative to the clone method. If not, then use the shortcut named set header.
    2. Add the authorization token: Add the authorization token in your code as given below. 

    Cancel the current Request

    Angular has a very convenient way to cancel the requests coming from the browser. Simply returning an empty object would cancel the request in no time. We have an example below where we are checking the login activity of a user.

    If the user is logged in, then the request continues, and if not, the request is canceled. Follow the below code and make changes wherever necessary.

    Change the Requested URL

    Angular provides a way to change a URL before it reaches the server. The URL property is enclosed within the HTTP request, and you can change it as per your requirement.

    If you want to add a base URL for all your HTTP requests, just replace HTTP with HTTPS, and your task is done. Here we have an example of how you can do it. Refer to the below code and follow the same.

    Looking to level up your coding skills? Discover the power of Python with our unique online course. Learn Python online and unlock endless possibilities. Join now!

    Real-Life Analogies for Creating an HTTP Interceptor 

    To better understand the significance of creating an HTTP interceptor, let's understand it with a few more everyday situations: 

    1. Airport Security: Just as airport security ensures the safety of passengers by intercepting and examining luggage, an HTTP interceptor will enhance the security of your application by inspecting and modifying HTTP requests and responses. 
    2. Mail Screening Process: Similar to how mail undergoes a screening process to detect and address potential threats, an HTTP interceptor will allow you to inspect and modify data flowing between your application and the server, thus ensuring a secure exchange. 

    Therefore, creating an HTTP interceptor in Angular is similar to implementing security measures in various aspects of our daily lives. 

    How to Use Angular Interceptors in Real-Life Secure API Communication 

    Now, a web developer — or more specifically, a full-stack developer — generally uses interceptors to pass essential tokens to a REST API for secure user authentication and authorization. These tokens act as digital keys, which grants the user access to protected resources based on user permissions. 

    Moreover, the interceptors in Angular play an important role by easily attaching and managing these tokens in HTTP requests, thus ensuring, that there is a standardized and secure approach to authentication across any developed application. They also centralize this process, by enhancing code maintainability and, in turn, further reducing redundancy in the token-handling logic. 

    In Angular, interceptors can be used to modify HTTP requests or responses globally before they are sent or after they are received. One common use case is to add authentication tokens to outgoing requests. Here's a simple example: 

    Let's assume, that you want to create an authentication service that handles the user's login and token management. Let’s learn how to do this by creating an interceptor to attach the authentication token for every outgoing HTTP request. 

    So first, you must create an authentication service as follows: 

    // authentication.service.ts 
    import { Injectable } from '@angular/core'; 
      
    @Injectable({ 
      providedIn: 'root', 
    }) 
    export class AuthenticationService { 
      getToken(): string | null { 
        // Logic to retrieve the authentication token from wherever it is stored 
        // For example, you might store it in localStorage after a successful login 
        return localStorage.getItem('authToken'); 
      } 
    } 

    Then, you must create the interceptor as shown previously: 

    // auth.interceptor.ts 
    import { Injectable } from '@angular/core'; 
    import { 
      HttpRequest, 
      HttpHandler, 
      HttpEvent, 
      HttpInterceptor, 
    } from '@angular/common/http'; 
    import { Observable } from 'rxjs'; 
    import { AuthenticationService } from './authentication.service'; 
      
    @Injectable() 
    export class AuthInterceptor implements HttpInterceptor { 
      constructor(private authService: AuthenticationService) {} 
      
      intercept( 
        request: HttpRequest<any>, 
        next: HttpHandler 
      ): Observable<HttpEvent<any>> { 
        // Get the authentication token 
        const authToken = this.authService.getToken(); 
      
        // Clone the request and add the token to the Authorization header 
        if (authToken) { 
          request = request.clone({ 
            setHeaders: { 
              Authorization: `Bearer ${authToken}`, 
            }, 
          }); 
        } 
      
        // Pass the request to the next handler 
        return next.handle(request); 
      } 
    } 
     

    Finally, In your `app.module.ts` or another module where your HTTP requests are configured, you will need to provide the interceptor as follows: 

    // app.module.ts 
    import { NgModule } from '@angular/core'; 
    import { BrowserModule } from '@angular/platform-browser'; 
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 
    import { AuthInterceptor } from './path/to/auth.interceptor'; 
      
    @NgModule({ 
      imports: [BrowserModule, HttpClientModule], 
      providers: [ 
        { 
          provide: HTTP_INTERCEPTORS, 
          useClass: AuthInterceptor, 
          multi: true, 
        }, 
      ], 
    }) 
    export class AppModule {} 

    Now, every HTTP request made by your Angular application will include the authentication token in the `Authorization` header, all because of the interceptor. 

    Can We Have Multiple Interceptors?  

    Absolutely, Angular is very much flexible! It allows us to incorporate multiple interceptors, each serving a unique purpose in shaping the communication flow of your application. Think of these interceptors as a team of specialists, each handling a specific aspect of the interaction. 

    For instance, let's think of another interceptor angular example, consider an e-commerce platform like Amazon, or Flipkart, where one generated interceptor in Angular focuses on modifying headers to personalise user experiences, while another will reshape the request body to ensure seamless data exchange. This collaborative effort enhances the overall functionality of the application. 

    Let’s add another layer to this angular http interceptor example, imagine a security system with multiple checkpoints. Each interceptor therefore acts as a checkpoint, performing its designated task - whether it's verifying credentials, enhancing security, or refining responses. Together, these interceptors create a robust defence mechanism for the application, allowing for a tailored and secure user experience. 

    Conclusion

    Hopefully, we could demonstrate all the possible facts and things related to the interceptors angular. Interceptors are a great way to make your code scalable to an extent. You can perform various actions just by creating HTTP interceptors in angular. So, if you want to study more about the angularJS, you must check our course KnowledgeHut’s AngularJS certification course.

    Frequently Asked Questions (FAQs)

    1Why do we use interceptors?

    Ans. Interceptors angular allows the developers to call the interceptor methods on the target classes with lifecycle events. They are used along with the java EE managed classes.

    2How do you write an angular interceptor?

    Ans. An angular HTTP interceptor uses an interface that implements its functionalities using different in-built methods and modules.

    3How do you use an interceptor in angular 11?

    Ans. The HTTP interceptor angular has the latest module added to the list. The HTTP client module modifies the HTTP requests before sending them to the back ends.

    4Can we have more than one interceptor in angular?

    Ans. Yes, you can have multiple angular interceptors by changing the value of multi to true. This will inform the classes regarding the usage of the angular HTTP interceptors.

    5Does the order of interceptors matter?

    Ans. Interceptors have a pre-defined order determined by the order in which they are declared. And, by default, they follow the same order, and so do the developers.

    6What is HTTPBackend in angular?

    Ans. The HTTPBackend is a service used in angular to model all the HTTP requests made by the application. It mentions the approximate requests and values to return for a specific request.

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon