How To Add An Authorization Header To HTTP Requests In Angular

Chances are that your single-page application built with Angular retrieves data from an API endpoint, and the endpoint is protected. One of the easiest and most simplest forms of protection may be an Api-Key which needs to be added to the header of every request to this endpoint.

Without delving deeper in to the pros and cons of using header keys (that’s beyond the scope of this post), let’s have a look at how you can add an Authorization key to all HTTP requests made in your Angular application.

How to add an Authorization Header to HTTP requests in Angular

I’ll assume you have an Angular project set up, and the Api-Key to hand.

Step 1: The first thing you need to do is create a HttpInterceptor. This is done by creating a service. If you have an Angular CLI project, you can simply run the following command:


ng generate service api-interceptor

If you are have structured your Angular app using multiple modules as I have previously outlined in this post, then you should run the following command:


ng generate service core/services/api-interceptor

To keep things simple and on-track, the remainder of this guide will assume you generated the service using the first command shown above.

Step 2: Next, adjust the class definition for this service to implement HttpInterceptor from the @angular/common/http library.

Typescript will then warn you that you must provide an implementation for the intercept() method.

The intercept() method has a signature of intercept(request: HttpRequest, next: HttpHandler): Observable> which means it takes an input parameter of a request and then a reference to the HttpHandler. We can set the header on the request object and then complete the process by calling the handle() method on the HttpHandler.

To do this, add the following code to your service:


@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    request = request.clone({
      setHeaders: {
        Authorization: `Api-Key YOUR_KEY_HERE`
      }
    });

    return next.handle(request);
  }
}

Remember to replace YOUR_KEY_HERE with your API key.

Now, every time a HTTP request is made by your application the following header will be added:


"Authorization": "Api-Key YOUR_KEY_HERE"

Subscribe to Email Updates