encode object into cookie string for testing

Viewed 204

I'm using cookies to pass the session about the logged in user, and on the server I can set and get them fine:

res.cookie("foo", { bar: "baz" })

// later on
console.log(req.cookies.foo) // { bar: "baz" }

Now, I want to test it, and I need to set the cookie header, but I don't know how to convert an object, i.e. { bar: "baz" }, to the header string the cookie evaluates to enter image description here

What's the algorithm used here?

(I'm using supertest but it shouldn't matter IMO)

1 Answers

In express by default the cookie is encoded, you need to pass the options to keep it as a string.

encode Function - A synchronous function used for cookie value encoding. Defaults to encodeURIComponent.

// Custom encoding
res.cookie("foo", { bar: "baz" }, {encode: String})

You can check here for more details.

Related