Exclude requests from being intercepted by Http Inspector Angular 5

Introduction

So angular 4.3 introduced a cool concept “Http Interceptors”. These can intercept your request and responses where you can modify them in a very clean way.

We use these interceptors for various purposes like adding an auth token to each request, to show a loading icon meantime the request is being processed etc.

One of the challenges that I faced is that these interceptors will catch all the request and responses and Angular 5 does not provide a clean way of excluding some request from being intercepted by a particular interceptor.

To tackle this situation below are the solutions that I could think of:

  • Creating a whitelist of URLs. The interceptor will skip those URLs present in the whitelist.

  • Creating a custom header and send the same with the request, when the interceptor finds the header it will skip the request removing the custom header.

I felt the second solution to be cleaner as the logic for whether the request will be intercepted or not was with the request rather than with the interceptor.

Below is a small example of how to achieve this:

 // example of intercept method in an interceptor
 intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    
    if(req.headers.has('DoNotIntercept')) {
      clonedRequest = clonedRequest.clone({
        headers: clonedRequest.headers.delete(
          'DoNotIntercept'
        )
      });
      return next.handle(clonedRequest);
    }
    else{
        // do some changes with the request as required
        return next.handle(clonedRequest);
    }
  }

  // sample request to avoid being intercepted
  export class SomeService {
  private headers = new HttpHeaders();
  constructor(private http: HttpClient) {
    this.headers = this.headers.append(
      'DoNotIntercept',
      'true'
    );
  }

  someMethod(someData): Promise<string> {
    return this.http
      .post<string>(`someUrl`, someData, {
        headers: this.headers
      })
      .toPromise()
      .then(
        result => {
            // do something
        }
      );
    }
  }

Cheers. And Keep hacking..