Search code examples
angularhttpclientangular-http-interceptors

The new headers are not added with the interceptor


I want to add headers to all HTTPClients in my Angular 8 application. This is my interceptor:

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

@Injectable()
export class Interceptor implements HttpInterceptor {
  constructor(private toaster: ToastrService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    alert('Interceptor!');

    // Set headers
    const headers = req.headers;

    // Set this header for security
    headers.set('test', 'value');

    const authReq = req.clone({ headers });

    return next.handle(authReq);
  }
}

The alert is executes but the test header is not added to the request.


Solution

  • From the official docs:

    You can't directly modify the existing headers within the previous options object because instances of the HttpHeaders class are immutable.

    Use the set() method instead. It returns a clone of the current instance with the new changes applied.

    You need to clone the request and set headers there.

    const newReq =  req.clone({ headers: req.headers.set('test', 'value') });
    return next.handle(newReq);