Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'ReferenceError: Headers is not defined' when using Headers in a server side rendered react project

I'm setting up a new application in React and I want it to be server side rendered. Unfortunately I'm not able to use Headers since it keeps throwing the error 'ReferenceError: Headers is not defined'.

I've already tried to add Headers by adding:

import fetch from 'node-fetch';

global.fetch = fetch
global.Headers = fetch.Headers;

This still throws the error though.

This is an example of how I'm currently implementing the headers:

const defaultOptions = {
  method: METHOD,
  headers: new Headers({
    'Content-type': 'application/json',
    'X-Request-ID': new Date().getTime().toString(),
  }),
};

Does anyone know what I'm missing to make it build and start?

like image 234
Chantal Avatar asked Jul 24 '19 15:07

Chantal


3 Answers

This worked for me

import fetch, {Headers} from 'node-fetch'

if (!globalThis.fetch) {
  globalThis.fetch = fetch
  globalThis.Headers = Headers
}

I wasn't able to call new fetch.Headers() as suggested by @eaccmk

like image 64
Tim Avatar answered Sep 29 '22 06:09

Tim


TL;DR Short Answer, use:

const fetch = require("node-fetch");

var myHeaders = new fetch.Headers();

More details: This was my error I was getting while running npm test

var myHeaders = new Headers();
                ^
ReferenceError: Headers is not defined

I found the answer in first line of official MDN page on Headers : https://developer.mozilla.org/en-US/docs/Web/API/Headers

The Headers interface of the Fetch API allows you.... So I tried this:

Old : var myHeaders = new Headers(); to
new : var myHeaders = new fetch.Headers();

like image 44
eaccmk Avatar answered Sep 29 '22 07:09

eaccmk


Do not use global in SSR, depending on the case it can cause some nasty bugs. For example while you are rendering one user, another one can request website and change the global variable while the first user still has some requests to do.

Regarding fetch - you can set headers like this:

   fetch('https://google.com', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
        }
     }
   );
like image 40
ewief Avatar answered Sep 29 '22 07:09

ewief