38

I'm trying to learn how to use HttpInterceptor to add a couple of headers to each HTTP request the app do to the API. I've got this interceptor:

import { Injectable } from '@angular/core';

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

import { Observable } from 'rxjs/Observable';


@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json')
    });

    console.log('Intercepted HTTP call', authReq);

    return next.handle(authReq);
  }
}

Apart of the 'Content-Type' header I need to add an 'Authorization' but I don't how to do it (the documentation of Angular HttpHeaders is just the list of the methods, without any explanation).

How can I do it? Thanks!

Fel
  • 3,126
  • 5
  • 30
  • 67
  • Check here https://www.freakyjolly.com/angular-7-6-handle-http-request-and-response-using-interceptors-in-angular-4-3-plus-versions/ – Code Spy Aug 07 '19 at 15:58

6 Answers6

60

Since the set method returns headers object every time, you can do this. This way, original headers from the intercepted request will also be retained.

const authReq = req.clone({
    headers: req.headers.set('Content-Type', 'application/json')
    .set('header2', 'header 2 value')
    .set('header3', 'header 3 value')
});
Ketan Patil
  • 993
  • 11
  • 20
  • 4
    This is usually the way you want to do it. The accepted answer will overwrite any previous headers, so if that's what you want to do, fine; but the the OP asked to "add" headers, not reset them all. – rodeo90 Oct 29 '18 at 20:00
  • 1
    This should be the accepted answer. Like stated above it will overwrite any headers already set. I was having that problem. This fixed it. – Skel Sep 03 '19 at 13:04
  • This is the right answer, it preserves existing headers. – abracadabrax Feb 28 '20 at 10:49
  • this is great for chaining interceptor headers. a preferred approach over the accepted answer – Vijay Jul 30 '20 at 19:51
  • this is the right approach as suggested by angular documentation. https://angular.io/guide/http#adding-and-updating-headers – quantumThinker Aug 17 '20 at 15:48
48

Edit: Following suggestions in comments I have unified both answers

Overwriting all headers

@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const authReq = req.clone({
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token'
    })
  });

  console.log('Intercepted HTTP call', authReq);

  return next.handle(authReq);
}

Adding more headers without overwriting (credits to Ketan Patil - see answer in this post)

const authReq = req.clone({
    headers: req.headers.set('Content-Type', 'application/json')
        .set('header2', 'header 2 value')
        .set('header3', 'header 3 value')
});
axl-code
  • 1,718
  • 1
  • 12
  • 21
  • 11
    What if you have multiple interceptors? This one would overwrite those headers set before, wouldn't it? – Marc Scheib Feb 08 '18 at 10:50
  • 1
    If you have more than one interceptor for http calls you should refactor your logic: having a parent class for dealing with headers or other common logic, etc. but that's a different question not included in this one ;) – axl-code Feb 08 '18 at 10:56
  • 1
    @MarcScheib check my answer. – Mihai Apr 06 '18 at 17:16
  • 1
    Its not good practise to overwrite your entire headers object. Anyone looking here should check the other answers below as they have much better solutions. – DoubleA Sep 11 '19 at 06:17
  • 2
    to include the original headers in the `new Headers()`... you just add `...req.headers` inside. `new HttpHeaders({ ...req.headers, 'Content-Type': 'application/json' })` – Pierre Apr 24 '20 at 15:39
  • 1
    And how is having more than once interceptor for HTTP calls bad logic? – Parziphal Aug 31 '20 at 19:07
22

As mentioned before - accepted method overrides headers, for adding them I like approach from API documentation:

const authReq = req.clone({ setHeaders: { Authorization: authToken } });
vitalii-patsai
  • 281
  • 2
  • 7
5
  const modifiedReq = req.clone({
      url: this.setUrl(req.url),
      headers: this.addExtraHeaders(req.headers)
    });

And the method:

private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
  headers = headers.append('myHeader', 'abcd');
  return headers;
} 

The method .append creates a new HttpHeaders object adds myHeader and returns the new object.

Using this solution means that you can also use multiple interceptors because you will not overwrite your headers.

Mihai
  • 1,029
  • 11
  • 21
2

in your interceptor file

import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const auth = req.clone({
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Auth-Token': 'jwtToken'
    })
  });



  return next.handle(auth);
}



 **in app module**

import {HTTP_INTERCEPTORS} from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    {provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true},
  ],
  bootstrap: [AppComponent]
})
Shashwat Gupta
  • 3,139
  • 23
  • 21
-2

I have tried following ways to send custom headers using interceptors. please check the link stackBlitz

Please refer the console screenshot for your reference browser console-request header

And the custom headers are added in

access-control-request-headers:authkey,content-type,deviceid

I want the headers to be added as part of header, not inside access-control-request-headers. Please suggest me on this

Dinesh N.K
  • 51
  • 1
  • 8