angularexpressxmlhttprequestangular-universalreferer

How to set "Referer" header in Angular universal Httpclient Xhr calls?


I have an Angular Universal SSR app that gets data from the API server with HttpClient. Everything works fine and I can Render data server-side.

The problem is I want to have client Referer which Browser Sets by default in CSR and sends data based on each site (I have multiple sites with different domains).

I get the referer with like this:

import { isPlatformBrowser } from '@angular/common';
import { REQUEST } from '@nguniversal/express-engine/tokens';
...

if (!this.isBrowser) {
  const serverRequest = this.injector.get(REQUEST) as Request;
  this.referer = `${serverRequest.protocol}://${serverRequest.get('Host')}`;
  console.log('refrerr is : ',this.referer) 
}

then I Set it in my header with:

request = req.clone({
    url: `${this.Config.url}${req.url}`,
    setHeaders: {
      referer: this.referer,
    },
    params
  });

But I get this err in the console :

Refused to set unsafe header "referer"


Solution

  • Try this

    npm install xhr2
    

    Then in your server.ts file

    import * as xhr2 from 'xhr2';
    
    //...
    xhr2.prototype._restrictedHeaders = {};