What is the difference between set cookie, res cookie and Cooki.set() (js-cookie)?

2.3k Views Asked by At

I am trying to implement an authentication system and I've run into some problems and after a lot of troubleshooting I've come to realise that I don't fully understand the difference between theese three:

res.cookie(name, value, [options])

and

res.setHeader('Set-Cookie')

and

Cookies.set(name, value, [options]) //js-cookie npm package
1

There are 1 best solutions below

0
On BEST ANSWER

I'm assuming that res.cookie (and res.setHeader) are coming from express.

Documentation for res.cookie states (just underneath the property table) that

All res.cookie() does is set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.

So, res.cookie is just a wrapper around res.setHeader to make the code clearer: you can pass options as an object, instead of manually constructing a header value.

Both of those are called on a res (a.k.a response) object, so it's a serverside tool to tell the client "please put that into cookies".

As for the last one, Cookies.set, that is intended to be run on the client instead. Internally, it just sets the document.cookie propery.

So, if we build a tl;dr table of all mentioned cookie setting options, here they are:

function side needs manual formatting
res.cookie server no
res.setHeader server yes
Cookies.set client no
document.cookie = client yes