Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CookieParser vs req.cookies expressjs

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?

like image 417
thefourtheye Avatar asked Dec 12 '13 17:12

thefourtheye


1 Answers

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.

like image 118
Lasse Avatar answered Sep 20 '22 06:09

Lasse