Tutorials

HTTP Interceptor Angular

If you are new to HTTP requests in Angular, check out our 5 minute guide.

Key Takeaways

  • The HttpInterceptor interface allows you to modify HTTP requests and responses globally in an Angular app.
  • You can use interceptors for caching, modifying headers, and logging requests.
  • Interceptors need to be provided before the HttpClient in the module setup for them to work properly.

The Angular HttpInterceptor

The HttpInterceptor interface lets you modify all HTTP requests in your Angular app. It’s perfect for tasks like caching responses, altering headers, and logging data.

Angular HttpInterceptor Examples

Basic Example

A simple implementation of the HttpInterceptor interface:

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

@Injectable()
export class MyInterceptorService implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    console.log(req.url);
    return next.handle(req);
  }
}

Implementing the HttpInterceptor requires defining an intercept() method that processes each HttpRequest and passes it to HttpHandler

Providing the HTTP Interceptor

Use HTTP_INTERCEPTORS to provide your interceptor in app.module.ts:

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptorService } from './my-interceptor.service';

@NgModule({
  ...
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptorService,
      multi: true
    }
  ]
})
export class AppModule {}

Adding multi: true allows for multiple interceptors to be provided, executed in the order listed.

Modifying the URL

Force all requests to use HTTPS:

@Injectable()
export class MyInterceptorService implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler) {
    const secureReq = req.clone({
      url: req.url.replace('http://', 'https://')
    });
    return next.handle(secureReq);
  }
}

Modifying Headers

Add an Authorization header:

@Injectable()
export class MyInterceptorService implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler) {
    const token = "YOUR_AUTH_TOKEN";
    const authReq = req.clone({
      headers: req.headers.set('Authorization', token)
    });
    return next.handle(authReq);
  }
}

Ensure that tokens are retrieved dynamically in a real application.

Caching Responses

Here's a sample caching interceptor:

@Injectable()
export class MyInterceptorService implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler) {
    const cachedResponse = localStorage.getItem(req.url);
    return cachedResponse 
      ? of(new HttpResponse(JSON.parse(cachedResponse)))
      : this.sendRequest(req, next);
  }

  sendRequest(req: HttpRequest, next: HttpHandler) {
    return next.handle(req).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          localStorage.setItem(req.url, JSON.stringify(event));
        }
      })
    );
  }
}

Using localStorage allows you to cache and reuse responses effectively.

Angular HTTP Interceptor not Working?

Check Your Imports

Make sure to use @angular/common/http as @angular/http is obsolete.

Provide Interceptors Before HttpClient

If interceptors are provided after HttpClient, they won’t work.

Interceptor Order Matters

Interceptors execute in the order they are provided. Make sure to check the sequence they are listed in.

FAQ

Can I have multiple HTTP interceptors in Angular?

Yes, using multi: true allows you to provide an array of interceptors.

What’s the primary benefit of using an interceptor in Angular?

Interceptors allow you to modify requests and handle responses globally, making code maintenance easier.

Why do I need to clone HttpRequest in an interceptor?

HttpRequest is immutable, so cloning is needed to modify it.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews