Posted on Updated on - Arjun

How to handle cookies in Express JS?

Cookies are very useful to store small piece of web application data and cookies are stored on the user’s computer by the user’s web browser while the user is browsing. Express uses the same methods, Cookies, as most other web frameworks to track sessions. A cookie will have the session ID so that Express can look it up on each request.

Express came up with cookie-parser middleware to handle Cookies, by using this module you can easily manage your express application Cookies.

handle cookies express js

Let’s install cookie-parser middleware through npm, issue below mentioned command from your terminal and project root folder where your package.json file resides.

lets use this middleware along with all the other middleware. Remember that the middleware is processed in order, so add it before other middleware so other middleware can use it.

The Cookie parser gives us access to req.cookies with an object keyed by the Cookie names. Optionally you may enable signed cookie support by passing a secret string, which assigns req.secret so it may be used by other middleware. you can access singed Cookies with req.signedCookies.

How to set Cookie

The res.cookie() function is used for setting Cookie

You can also set additional options of Cookies by passing an object as 3rd argument to the above function. let set maximum age of a Cookie.

You can tell Express to set your Cookie only over HttpOnly.This flag will tell browsers to not allow client side script access to the Cookie.

You can tell express to use https encrypted channel to exchange cookie data with secure flag.

You can all so set Cookie expire time in milliseconds.

Reading Cookies?

You can access your Cookies via request object, req.cookies.cookie_name or req.cookies, second one return all the app cookies where first one return only the specific cookie. If the request contains no Cookies, it defaults to {}.

Deleting cookie?

You can also easily deleted Cookies by using response object’s clearCookie function, which accepts the name of the Cookie which you want to delete. You can also delete your Cookies from browser developers tools.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status