HTTP Interceptor guide: Angular 17

Bittu Kumar
2 min readJun 28, 2024

--

If you need to perform some actions on every HTTP request or response
( like adding headers, logging, error handling, modifying request parameters ) , HTTP interceptor is a way to go to achieve this functionality.

Interceptors are a powerful feature of Angular for managing HTTP communications in a centralized way.

In this article, We will explore functional based interceptor which is newly introduced.

Some of the use case where we should use interceptor:

  • to handle HTTP requests and responses globally,
  • allowing for centralized management of tasks like adding headers, logging, authentication, and error handling

Assuming you are using angular 17, You will be having app.config.ts, There you need to set it up HTTP client

// app.config.ts

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import {provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './interceptors/auth.interceptor';

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

We will create interceptor by this command:

ng generate interceptor auth
// auth.interceptor.ts

import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { FirebaseAuthService } from '../services/firebase-auth.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
// const authToken = localStorage.getItem('authToken');
const token= inject(FirebaseAuthService)
const authToken= "Your auth token";
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`
}
});
return next(authReq);
};

Now once you do api calling, You will see Authorization in request header in each request in your project.

I have created demo application in angular 17, where I have implemented functional based interceptor.

This application contains Angular with firebase (Login, signup, logout ) features.

Github Repo link: https://github.com/bittu1040/snippets-app

Thanks for reading till here, You can follow me if you like this article and learnt something new.

You can find me here for any further discussion:

https://www.linkedin.com/in/bittukumar-web/

--

--