Angular 17: HTTP Interceptors guide

Mohsin Ansari
4 min readMar 4, 2024

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.

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 serve as a centralized mechanism for executing logic before or after an HTTP request is made or a response is received. This eliminates the need to scatter logic across multiple components or services, promoting code reusability and maintainability.

2) Authentication and Authorization:

Interceptors offer an elegant solution for handling authentication and authorization-related concerns. By intercepting outgoing requests, developers can seamlessly append headers, tokens, or perform authentication checks without cluttering the application codebase.

3) Error Handling:

Intercepting HTTP responses enables developers to implement robust error-handling mechanisms. Interceptors can intercept error responses, transform them into meaningful messages, and streamline error propagation throughout the application.

4) Request and Response Transformation:

With interceptors, developers can effortlessly transform request payloads or response data. This enables scenarios such as request/response logging, data serialization/deserialization, or response mapping to domain models.

Implementation in Angular

Angular’s HTTP Interceptors are seamlessly integrated into the Angular framework, offering a streamlined approach to intercepting HTTP traffic. Below is the implementation of the HTTP Interceptor in Angular 17 standalone project.

In this interceptor we will just add an authorization header in the request and also handle the errors.

  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. Now generate an interceptor using below angular cli command

ng generate interceptor demo

it will generate below files

5. Add below code in demo.interceptor.ts to implement an interceptor which will add an authorization header in every 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);
};

configuring the interceptor by calling withInterceptors and passing our interceptor to it

// app.config.ts

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

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

now in every HTTP request it will send authorization header, you can inspect in the browser and in request headers you can check

6. Handle errors

Instead of handling errors inside components we can write our logic in the interceptor itself to handle the errors

// 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 means less repetitive code and better organization.
  • They make your applications more reliable and efficient.
  • Use them for security, error handling, and many other enhancements.

Get the source code from below repo

--

--

Mohsin Ansari

A software developer interested in ReactJs, ExpressJs and Angular