When I read about req.cookies in expressjs docs,
When the cookieParser() middleware is used this object defaults to {}, otherwise contains the cookies sent by the user-agent.
And when I read about CookieParser middleware,
Parses the Cookie header field and populates req.cookies with an object keyed by the cookie names.
So, req.cookies says if I use CookieParser, it will be set to {}, but CookieParser says it will populate req.cookies.
My question is Why do we need CookieParser, if req.cookies itself gives the cookies?
Without using cookieParser, cookies come as an URL-encoded header ("Cookie").
This means that, by default, the cookie information is to find in req.headers.cookie.
As the name implies, cookieParser parses the contents of the Cookie header (utilizing the aptly-named cookie-module) and conveniently places the result (an object keyed by the cookie names) in req.cookies for your enjoyment.
I'd encourage you to look at the source code of cookieParser to better understand why it even exists in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With