How to intercept XMLHttpRequest (Xhr) requests in Angular + HttpInterceptor

Balram Chavan
5 min readAug 3

The Angular provides HttpInterceptor to intercept all network requests made by Http or HttpClient service so that you can add headers like Authorization or AppId tokens. But it doesn’t intercept XmlHttpRequest (XHR) requests made explicitly. In this story, we will see how to intercept XHR requests in Angular.

Angular HttpInterceptor:

When you have to pass specific headers or modify the response of REST APIs consumed in Angular application, HttpInterceptor provide a solution to do in a central place. For example, Authorization header where you can pass Auth tokenBearer <auth-token> by reading it from local state or service. Or adding AppId or ApiKeyheaders where you specify these values to consume secured APIs.

Here is the simple HttpInterceptor example where we are passing DUMMY_AUTH_TOKEN value in Authorization token.

You can see the Authorization header is added to outgoing request.

Angular Interceptor does more than just passing the headers. Checkout the official documentation to see how to log requests/response, cache requests.

XMLHttpRequest originating from third party components

If you are consuming REST APIs via Http (obsolete) or HttpClient services, and you have configured the HttpInterceptor properly in a single AppModule providers, then you wouldn’t need to worry about this situation. All requests shall be intercepted by HttpInterceptor.

However, you may come across a situation where you are using a third party component library which internally fires the XMLHttpRequests to configured REST APIs. For example, you might be using a third party File Explorer component to list files from your API services, Azure Blob Storage or AWS S3…