How To Handle Cookies In Node.js Express App

    Sep 20, 2018       by Pankaj Kumar
cookies.jpg

A cookie is a mechanism that allows the server to store its own information about a user on the user's own computer. You can view the cookies that have been stored on your hard disk (although the content stored in each cookie may not make much sense to you). The location of the cookies depends on the browser.

 

To use cookies in nodejs express application, we use cookie-parser package of npm, By using this package we can easily manage the express  application cookies.

 

Install package

npm install  cookie-parser 

 

Use this middleware

const express = require('express');

const cookieParser = require('cookie-parser');

const app = express();

// adding cookieParser to middleware stack

app.use(cookieParser());

 

 

The module gives us access to req.cookies with an object keyed with the cookie name. We can also enable signed cookie support by passing a secret string, Which assigns req.secret.

 

Set Cookie

 

 
app.get('/cookie',function(req, res){
let minute = 60 * 1000;
res.cookie(cookie_name, 'cookie_value', { maxAge: minute });
return res.send('cookie has been set!');
});
 

 

In the above code, We have set the maximum age of a Cookie, Which is optional. We can also set the expire time in milliseconds like below

res.cookie(cookie_name , 'cookie_value', {expire : 24 * 60 * 60 * 1000 });

 

We can also set cookie only over HttpOnly.This flag tells the browsers to not allow client-side script access to the Cookie.

 

res.cookie(cookie_name , 'cookie_value', { HttpOnly: true});

 

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

res.cookie(cookie_name , 'cookie_value', { secure: true});

 

Read Cookies

We can access Cookies via request object, req.cookies.cookie_nameor req.cookies.

 

Delete cookies

W can also easily delete Cookies by using res.clearCookie function, which accepts the name of the Cookie which we want to delete. W can also delete Cookies from browser developers tools.

 

 
app.get('/deletecookie', function(req,res){
res.clearCookie('cookie_name');
res.send('Cookie deleted');
});
 

 

Conclusion

So in this article, We learn all about cookies in Node.js express application.

 

That’s all for now. Thank you for reading and I hope this article will be very helpful to understand how to handle cookies in node.js express application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


WHAT'S NEW

Find other similar Articles here: