Leveraging HTTP Interceptors for Enhanced API Management in Angular

Gili Yaniv
3 min readSep 11, 2023

--

Photo by Luke van Zyl on Unsplash

HTTP Interceptors are a powerful feature in Angular that allows developers to intercept and manipulate HTTP requests and responses. They provide a way to centralize common functionality such as authentication, logging, error handling, and more. In this article, we will explore the concept of HTTP Interceptors and demonstrate how to use them effectively in Angular.

What is an HTTP Interceptor?

An HTTP Interceptor in Angular is a middleware that can be used to intercept incoming and outgoing HTTP requests and responses. Interceptors are implemented as Angular services, and they can be added to the HTTP request/response pipeline to perform various tasks before the request is sent to the server or after the response is received. This makes them incredibly useful for tasks like adding headers, handling errors, or logging API requests.

How to Create an HTTP Interceptor in Angular

To create an HTTP Interceptor in Angular, you need to implement the HttpInterceptor interface, which requires you to define the intercept method. Here's a basic structure of an HTTP Interceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Your interceptor logic goes here
return next.handle(request);
}
}

In the intercept method, you can modify the request, observe the response, and return the modified request or response using RxJS observables. The next parameter is crucial, as it allows you to pass control to the next interceptor or the HTTP client itself.

Example 1: Adding Headers

One of the most common use cases for HTTP Interceptors is adding headers to outgoing requests. For instance, you may want to include an authentication token in every API request. Here’s an example of how to create an interceptor to add an authentication header:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Add authentication header
const token = 'your-auth-token';
const authRequest = request.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next.handle(authRequest);
}
}

To use this interceptor, you need to provide it in your Angular module’s providers array:

@NgModule({
imports: [HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
export class AppModule { }

Now, every outgoing HTTP request will automatically include the “Authorization” header with your authentication token.

Example 2: Error Handling

HTTP Interceptors can also be used for global error handling. For instance, you can create an interceptor to catch HTTP errors and handle them consistently throughout your application:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
// Handle the error here
console.error('HTTP Error:', error);
return throwError(error);
})
);
}
}

Again, remember to provide this interceptor in your Angular module.

Conclusion

HTTP Interceptors in Angular are a versatile tool for managing HTTP requests and responses. They allow you to centralize and reuse common functionality, such as authentication, headers, error handling, and logging, making your code more maintainable and robust. By implementing interceptors, you can ensure consistent behavior across your application and simplify the management of API-related tasks. Whether you are building a small application or a large-scale enterprise solution, understanding and utilizing HTTP Interceptors is a valuable skill for any Angular developer.

Follow me on Twitter, Medium, and Linkedin to read more!

--

--

No responses yet