Search code examples
javascriptgithub-apinode-fetch

How to pass Github Auth token in Node Fetch?


I'm currently dealing with API rate:

API rate limit exceeded. 
(But here's the good news: 
Authenticated requests get a higher rate limit. Check out the documentation for more details.)

I've tried multiple different methods, but seems like I'm missing something, here is my current state:

const TOKEN = process.env.GITHUB_TOKEN;

  try {
    return await fetch(
      url +
        new URLSearchParams({
          method: "GET",
          headers: {
            Authorization: `Bearer ${TOKEN}`,
          },
        })
    ).then((res) => res.json());
  } catch (err) {
    console.log("Error at Get Pulls", err);
  }

I've tried with Bearer, without, with lowercase, but at the end I always get the same error.


Solution

  • You are passing the headers and method inside the URLSearchParams, which is wrong. You must pass these properties to the fetch method.

    URLSearchParams is a helper to work with the query string of a URL.

    So do this instead

    await fetch(url, {
        method: "GET",
        headers: {
            Authorization: `Bearer ${TOKEN}`,
        },
    }).then((res) => res.json());