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?
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
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();
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',
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With