Express.js Cookies

Cookies are pieces of content that are sent to a user's web browser. In this, the server sends a bit of information and the browser stores it for a specified period of time. Cookies can enable you to make shopping cart, client groups, and customized destinations. It's not prescribed that you store sensitive data in a cookie, but you can store a unique identification string that will coordinate a user with information held safely in a database.


express.cookieParser()

To use cookies in express.js, first we need to include the cookie-parser middleware. The express.cookieParser() allows us to access user cookie values from the req.cookie object in request handlers.


Install cookie-parser

npm install --save cookie-parser

Use cookie-parser

To set and access the cookies in your app, you need to include the cookie-parser middleware.

app.use(express.cookieParser());

Set cookies

The res.cookie() function is used to set cookie values.

res.cookie('user', 'smith');

This method also has different properties that we can set in the third parameter like cookie expiration time, set the secure flag, etc.

Set Cookie Expiration Time

We can set cookie expiration time either by using expire keyword or by using maxAge property.

app.get('/cookie',function(req, res){
    res.cookie(name, 'value', { maxAge: 60000 }); 
});

In the above code, the cookie will get expire after 60000 ms. Alternatively we can set cookie expiration time by using expire keyword.

app.get('/cookie',function(req, res){
    res.cookie(name, 'value', {expire: 60000 + Date.now()}); 
});

Retrieve the value of cookie

We can access cookie by using request object, for example-

var name = req.cookie.user;

the above example returns one specific cookie value, to return all the set cookies use res.cookies.

var cookies  = req.cookies;

Delete a cookie

The clearCookie method is used to delete cookies.

res.clearCookie('user');






Read more articles


General Knowledge



Learn Popular Language