Sekrab Garage

An xhr2 explicit exclusion of the cookie

Angular SSR Refused to set unsafe header

Tip August 26, 23
Subscribe to Sekrab Parts newsletter.

I've been trying to fix a bug where I was making an http call to my local host, to get list of categories. The host written in expressjs had a middlewear to check for country code in cookies, before pinging a public URL to get country from IP address. (I was using the generous free tier of IPInfo.io). On client side everything worked perfectly well, since calling Http from the browser wrapped the header with all cookies found on the same host.

The problem was on SSR (Angular Universal using ngExpressEngine). When JavaScript is disabled, to test, fetching another URL is via xhr2 library. After digging for couple of days, it turned out, the library explicitly excludes cookies from headers, and throws error:

Refused to set unsafe header

Here is the code line in question.

if @_restrictedHeaders[loweredName] or /^sec\-/.test(loweredName) or
    /^proxy-/.test(loweredName)
    console.warn "Refused to set unsafe header \"#{name}\""
    return undefined
      
_restrictedHeaders:
    'accept-charset': true
    'accept-encoding': true
    'access-control-request-headers': true
    'access-control-request-method': true
    connection: true
    'content-length': true
    cookie: true
    cookie2: true
    date: true
    dnt: true
    expect: true
    host: true
    'keep-alive': true
    origin: true
    referer: true
    te: true
    trailer: true
    'transfer-encoding': true
    upgrade: true
    via: true

There is no check for withCredentials, and someone already opened an issue about it years ago.

So until then, I can only fix this problem in one of two ways, both ugly.

  • Use custom headers for these local calls.
  • Let the local interceptor call a nodeJs function instead of an http call. (I haven't figured this one out yet, but it looks promising).

Until then, keep those bugs out.