Comprehensive Guide to HTTP Interceptors in Angular 17

6 min read
May 24, 2024

In an Angular application, HTTP Interceptors offer a streamlined and centralized method to execute actions on each HTTP request or response, such as appending an authorization header. This allows your components to remain focused on their primary functions. Furthermore, interceptors can enhance error management, logging, and even modify request or response data dynamically, all while keeping your application code uncluttered.

Angular 17: HTTP Interceptors guide, In your Angular application If you need to perform actions on every HTTP request or response (like adding an authorization header), HTTP Interceptors provide a clean and centralized way to do it. This keeps your components focused on their core logic. Additionally, interceptors can streamline error handling, logging, and even modify request/response data on the fly — all without cluttering your application code.
HTTP Interceptor

Why Do We Need Interceptors?

1) Centralized Logic:

Interceptors act as a main tool for running logic either before an HTTP request is sent or after a response comes back. This approach removes the need to spread logic throughout various components or services, enhancing both code reusability and maintainability.

2) Authentication and Authorization:

Interceptors provide a refined approach to managing authentication and authorization issues. They work by capturing outgoing requests, allowing developers to effortlessly add headers, tokens, or carry out authentication checks without complicating the application's codebase.

3) Error Handling:

Catching HTTP responses allows developers to create effective error-handling strategies. Interceptors can catch error responses, convert them into understandable messages, and simplify the propagation of errors across the application.

4) Request and Response Transformation:

Using interceptors, developers can easily modify request payloads or response data. This allows for use cases like logging requests and responses, serializing or deserializing data, or mapping responses to domain models.

Implementation in Angular

Angular’s HTTP Interceptors are smoothly woven into the framework, providing an efficient method for intercepting HTTP requests and responses. Here’s how to implement the HTTP Interceptor in an Angular 17 standalone project.

In this interceptor, we will include an authorization header in the request and manage any errors that arise.

  1. Create a new Angular project
ng new test-app

2. First setup the HTTP client

// app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(),
],
};

3. Let’s make a HTTP request

// app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'test-app';

constructor(private http: HttpClient){}

callApiHandler(){
this.http.get('https://www.example.com').subscribe((res)=>{},)
}
}
// app.component.html

<div>
<button (click)="callApiHandler()">Test</button>
</div>

4. Next, create an interceptor by using the Angular CLI command shown below.

ng generate interceptor demo

it will generate below files

5. Incorporate the following code into demo.interceptor.ts to create an interceptor that appends an authorization header to each HTTP request.

// demo.interceptor.ts

import { HttpInterceptorFn } from '@angular/common/http';

export const demoInterceptor: HttpInterceptorFn = (req, next) => {
const authToken = 'YOUR_AUTH_TOKEN_HERE';

// Clone the request and add the authorization header
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});

// Pass the cloned request with the updated header to the next handler
return next(authReq);
};

By setting up the interceptor, we can do this by using the 'withInterceptors' method and giving it our interceptor as an argument.

// app.config.ts

...
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { demoInterceptor } from './demo.interceptor';

export const appConfig: ApplicationConfig = {
providers: [
...
provideHttpClient(withInterceptors([demoInterceptor])),
],
};

Now, each HTTP request will include an authorization header. You can inspect this in your browser by looking at the request headers.

6. Handle errors

Rather than managing errors within components, we can implement our error-handling logic directly in the interceptor.

// demo.interceptor.ts

import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';

export const demoInterceptor: HttpInterceptorFn = (req, next) => {
...
...
return next(authReq).pipe(
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
// Handle HTTP errors
if (err.status === 401) {
// Specific handling for unauthorized errors
console.error('Unauthorized request:', err);
// You might trigger a re-authentication flow or redirect the user here
} else {
// Handle other HTTP error codes
console.error('HTTP error:', err);
}
} else {
// Handle non-HTTP errors
console.error('An error occurred:', err);
}

// Re-throw the error to propagate it further
return throwError(() => err);
})
);;
};

Conclusion

  • Interceptors streamline common tasks across your app. This results in reduced repetitive code and improved organization.
  • They enhance the reliability and efficiency of your applications.
  • Employ them for security, managing errors, and a variety of other improvements.

Read more in Tech