Express Cookies

In order to use cookies functionality we need a cookie-parser middleware. We have already installed it in the beginning.

Lets modify our server.js with below code.
var express = require('express');  
var cookieParser = require('cookie-parser');  
var app = express();  
app.use(cookieParser());  
app.get('/cookieset',function(req, res){  
res.cookie('cookie_name', 'cookie_value');  
res.cookie('company', 'salesforcedrillers');  
res.cookie('name', 'gopal');  
  
res.status(200).send('Cookie is set');  
});  
app.get('/cookieget', function(req, res) {  
  res.status(200).send(req.cookies);  
});  
app.get('/', function (req, res) {  
  res.status(200).send('Welcome to Salesforcedrillers!');  
});  
var server = app.listen(8080, function () {  
  var host = server.address().address;  
  var port = server.address().port;  
  console.log('Example app listening at http://%s:%s', host, port);  
}); 

We have added a cookie-parser module to our application. It will help us by adding the cookie object to req and res object. To set a cookie, we use res.cookie and to fetch cookie we use req.cookie.

We can run the code using node server.js and the output shows as in below screen shot.

express-cookies

Below screenshot shows the output on the browser.

express-cookies-output

SET Cookie

Lets set the cookie using the below url.

http://127.0.0.1:8080/setcookie
Below screenshot shows the output on the browser.

express-cookie-set

GET Cookie

Lets fetch the cookie using the below url.

http://127.0.0.1:8080/getcookie
Below screenshot shows the output on the browser.

express-cookie-get

Subscribe Now