Search code examples
angulartypescriptangular-http-interceptors

Adding logic whether to add headers or not to req.clone in an Angular HttpInterceptor


I would like to add an if statement to the following logic inside of my HttpInterceptor:

const authToken = this.auth.getAuthorizationToken();

const authReq = req.clone({
     headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});

I would like to check if authToken exists prior to updating the headers with the authToken. I am pretty sure this is either a syntax thing or there is another way to set the headers property of req.clone() in a code block or something.

Here is my best shot at our but I feel like there is a better way to do it:

let authReq: HttpRequest<any> = req;

if (authToken) {
  authReq = req.clone({
    headers: req.headers.set('Authorization', `Bearer ${authToken}`)
  });
}

Solution

  • You are on the right track. You need to modify the request if the token exist or leave it unchanged if there is no token. Example:

    intercept(
      req: HttpRequest<any>,
      next: HttpHandler,
    ): Observable<HttpEvent<any>> {
      const authToken = this.auth.getAuthorizationToken();
    
      if (authToken) {
        req = req.clone({
          headers: req.headers.set('Authorization', `Bearer ${authToken}`)
        });
      }
    
      return next.handle(req);
    }