Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send cookies with node-fetch?

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.

like image 335
Skay Avatar asked Jan 15 '16 16:01

Skay


People also ask

Can you use fetch on node?

Fetch is already available as an experimental feature in Node v17. If you're interested in trying it out before the main release, you'll need to first download and upgrade your Node. js version to 17.5.

How do I send cookies in a post request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

How do I request a cookie in node JS?

If you do actually have the right cookie in your node. js code, then you can set it on your request like this: request({url: 'http://localhost:3000/users/api', headers: {Cookie: somedataHere}}, function(error, response, body) { console. log(body); //this console.


3 Answers

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);
like image 103
plemarquand Avatar answered Oct 19 '22 06:10

plemarquand


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',
  });
like image 45
zurfyx Avatar answered Oct 19 '22 05:10

zurfyx


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;
like image 2
Caojs Avatar answered Oct 19 '22 05:10

Caojs