graphql-request: ReferenceError: Headers is not defined with 3.1.0

Hi I just tried this library for the first time with your example code `const { GraphQLClient, gql } = require(‘graphql-request’);

async function main() { const endpoint = ‘https://graphql.contentful.com/content/v1/spaces/

const graphQLClient = new GraphQLClient(endpoint, {
    headers: {
        Authorization: 'Bearer <TOKEN>',
    },

})

const query = gql`
  query page {
      pageCollection(preview: true) {
        items {
          route,
          contentCollection {
            items {
              type,
              data
            }
          }
        }
      }
}

`

const data = await graphQLClient.request(query)
console.log(JSON.stringify(data, undefined, 2))

}

main().catch((error) => console.error(error))`

Which resulted in the error “ReferenceError: Headers is not defined” the error was only displayed when the headers field was present if I removed the headers no error was given. Downgrading to version 3.0.0 fixed the issue

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 40
  • Comments: 19

Commits related to this issue

Most upvoted comments

Solution for Node in plain JS:

const { GraphQLClient } = require('graphql-request');
const { Headers } = require('cross-fetch');

global.Headers = global.Headers || Headers;

const graphqlClient = new GraphQLClient(YOUR_URL, {
  headers: {
    authorization: YOUR_TOKEN,
  },
});

I’m using TypeScript and workaround like below helped me.

import { GraphQLClient } from "graphql-request";
import { Headers } from "cross-fetch";

// @ts-ignore
global.Headers = global.Headers || Headers;

const client = new GraphQLClient(YOUR_URL_HERE);

Importing the polyfill from cross-fetch fixed the issue for me:

import 'cross-fetch/polyfill';

Hi, instead of headers: {} use Headers: {}, it helped me example:

const client = new GraphQLClient(url, { Headers: { authorization: `Bearer ${JWT}` })

Hi,

I can confirm that. It worked like a charm before updating to the latest version.

const { GraphQLClient } = require("graphql-request");

const client = new GraphQLClient(url);

client.setHeaders({ authorization: `Bearer ${JWT}` });

return client;

@madikun are you sure about that? I tried it and while it got rid of the error it also didn’t send the authorization Token for me.

in case it helps anyone, Authorization needed to be capitalized for me

  const graphQLClient = new GraphQLClient(PROD_GRAPHQL_URL, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

they now use cross-fetch which totally breaks custom node-fetch usage, notably cookies as described in the readme 😒

supposedly-native ‘Headers’ class seems to be the issue

----> graphql-request/dist/index.js replace

if ( headers instanceof Headers)

by

if ( ‘undefined’ !== typeof Headers && headers instanceof Headers)

and it reworks instanceof Heavens