How to send cookies with node-fetch?

Javascriptnode.jsNode Fetch

Javascript Problem Overview


I've got nodejs application which handles user's requests and receives cookies which i want to proxy to internal API service. How to approach this by using node-fetch?

Don't offer superagent please.

Javascript Solutions


Solution 1 - Javascript

You should be able to pass along cookies by setting it in the header of your request:

const opts = {
    headers: {
        cookie: 'accessToken=1234abc; userId=1234'
    }
};
const result = await fetch(`/some/url`, opts);

Solution 2 - Javascript

Read & write cookies like a bot

async function login() {
  return fetch('<some_url>/login', {
      'headers': {
          'accept': '*/*',
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'cookie': '',
      },
      'body': 'username=foo&password=bar',
      'method': 'POST',
  });
}

(async() => {
  const loginResponse = await login();
  const loginCookies = parseCookies(loginResponse);
})();

You may want to include: accept-language, user-agent, referer, accept-encoding, etc. (check a sample request on your Chrome DevTools via the Network tab)

For some reason the resulting cookies of node-fetch requests are not compatible with new requests, but we can parse them like this:

function parseCookies(response) {
  const raw = response.headers.raw()['set-cookie'];
  return raw.map((entry) => {
    const parts = entry.split(';');
    const cookiePart = parts[0];
    return cookiePart;
  }).join(';');
}

Pass cookies in your future requests through the same headers:

  return fetch('<some_url>/dashboard', {
    'headers': {
        'accept': '*/*',
        'cookie': parsedCookies,
    },
    'method': 'GET',
  });

Solution 3 - Javascript

For simple, you can write a middleware which will include the cookies to global.fetch, like below.

const realFetch = fetch;

function cookieFetch(fetch, cookie) {
  return (url, opts) => {
    opts = opts || {};
    return fetch(url, Object.assign(opts, {
      headers: Object.assign(opts.headers || {}, { cookie })
    }));
  };
}

function middleware(req, res, next) {
  const kuki = req.headers.cookie;
  global.fetch = kuki ?
    cookieFetch(realFetch, kuki) :
    realFetch;
  next();
}

module.exports = middleware;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkayView Question on Stackoverflow
Solution 1 - JavascriptplemarquandView Answer on Stackoverflow
Solution 2 - JavascriptzurfyxView Answer on Stackoverflow
Solution 3 - JavascriptCaojsView Answer on Stackoverflow