node.jscookiesfetch

Node.js v20 global fetch not returning cookies


This endpoint sets a cookie, then redirects to a list of cookies:

https://httpbin.org/cookies/set/king/cole

When I go there in a browser, I get the expected result:

{
  "cookies": {
    "king": "cole"
  }
}

I get the same result when in the browser's console:

const res = await fetch('https://httpbin.org/cookies/set/king/cole')
await res.json()
// -> { cookies: { king:cole }}

But, if I execute those lines in Node, I get an empty set:

// Welcome to Node.js v20.12.0.
// Type ".help" for more information.
const res = await fetch('https://httpbin.org/cookies/set/king/cole')
await res.json()
// -> { cookies: {} }

Adding credentials: 'include' to the fetch doesn't help (and shouldn't be necessary?)

How can I get this to work?


Solution

  • Nodejs does not, by default, maintain cookies for you. You have to do that manually.

    So, you send the first request: https://httpbin.org/cookies/set/king/cole and get the cookie back in the response, but then when it redirects to https://httpbin.org/cookies, nodejs does not send the previous cookies back to the server on that redirect. Therefore, the server gets the redirect request with no cookies on it and that's what it shows you.

    For node-fetch, there are NPM modules that will act as a cookie jar and manage cookies for you (similar to what the browser does). On first glance, I don't see anything in NPM for the fetch() interface, but I'd be surprised if someone hasn't implemented it somewhere.