Express.js Cookies

What are cookies

Cookies are small piece of information i.e. sent from a website and stored in user's web browser when user browses that website. Every time the user loads that website back, the browser sends that stored data back to website or server, to recognize user.

cookies in express.js

Install cookie

You have to acquire cookie abilities in Express.js. So, install cookie-parser middleware through npm by using the following command:

Express.js Cookies 1

Import cookie-parser into your app.

snippet
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());

Define a route:

Cookie-parser parses Cookie header and populate req.cookies with an object keyed by the cookie names.

Let's define a new route in your express app like set a new cookie:

snippet
app.get('/cookie',function(req, res){
     res.cookie('cookie_name' , 'cookie_value').send('Cookie is set');
}); 
app.get('/', function(req, res) {
  console.log("Cookies :  ", req.cookies);
});

Browser sends back that cookie to the server, every time when it requests that website.

Express.js Cookies Example

File: cookies_example.js

snippet
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', 'rookienerd');
res.cookie('name', 'sonoo');

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 rookienerd!');
});
var server = app.listen(8000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});
ExpressJs cookies 2

Output:

Open the page http://127.0.0.1:8000/ on your browser:

ExpressJs cookies 3

Set cookie:

Now open http://127.0.0.1:8000/cookieset to set the cookie:

ExpressJs cookies 4

Get cookie:

Now open http://127.0.0.1:8000/cookieget to get the cookie:

ExpressJs cookies5
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +