Categories
Express.js

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.

npm install cookie-parser --save

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.

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

const app = express();
// add cookieParser to middleware stack
app.use(cookieParser());

// for signing the cookies.
//app.use(express.cookieParser('my secret here'));

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

app.get('/cookie',function(req, res){
    res.cookie(cookie_name , 'cookie_value');
    return res.send('cookie has been set!');
});

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.

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!');
});

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.

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

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

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

You can all so set Cookie expire time in milliseconds.

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

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.

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

By Praveen Anaparthi

11+ years of IT industry experience holding a wide range of skill sets and roles with significant work on PHP, Node.js, Python, Ruby, Docker, React.js, Microsoft Azure, Azure DevOps, Windows PowerShell, Shell script, Jenkins, MongoDB, SQL, MySQL, Apache, Nginx. etc. It is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

Leave a Reply

Your email address will not be published.