75

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Skay
  • 9,343
  • 6
  • 27
  • 28

3 Answers3

100

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);
plemarquand
  • 1,866
  • 2
  • 16
  • 20
45

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',
  });
leumasme
  • 376
  • 4
  • 19
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • 15
    "You may want to include: accept-language, user-agent, referer, accept-encoding, etc. (check a sample request on your Chrome DevTools)"; pro tip, to spare you the hassle: right click the request in the Network tab in Devtools, select copy, then select "Copy as fetch" and paste fetch function call code in editor. under-voted answer btw. +1. – Wis Jun 10 '19 at 18:42
  • In my case I just needed to adjust my code to use the method you showed in `parseCookies`. I didn't need to set any headers aside from that to get it working. This is indeed an undervoted answer. – wgwz Jan 31 '23 at 22:16
2

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;
Caojs
  • 175
  • 7