HTTP Interceptor guide: Angular 17
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.
Global Error handling Interceptor example:
// app.config.ts
provideHttpClient(
withInterceptors([errorInterceptorFn]
)
// error Interceptor
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 0) { // Client side error
toastr.error('No internet connection.');
} else { // Server side error
switch (error.status) {
case 401:
toastr.warning('Unauthorized. Please log in again.');
router.navigate(['/login']);
break;
case 403:
toastr.error('Forbidden. Permission issue.');
break;
case 404:
toastr.info('Requested resource not found.');
break;
case 500:
toastr.error('Server error. Please try again later.');
break;
default:
toastr.error('Unexpected error. Please try again.');
}
console.error(`Error ${error.status}:`, error.message);
}
return throwError(() => error);
})
);
};
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: