How to Node JS- Cookie-Parser & Express-session

In this tutorial, we are going to learn about two different middlewares in Node JS: Cookie-Parser & Express-session.  Let’s discuss the each of middleware.

Cookie Parser

A Cookie parser looks at the headers in between the client and server transactions and read those headers and parses out the cookies that are being sent.

 

Express session

The express session allows us to authenticate transactions between the client and the server. So, essentially, it lets the server note that the client is the same person that they have been talking to. It keeps bad people away from watching your connections.

Configuration

Let’s start the installation of those middlewares to the Node JavaScript Runtime Environment.  To install latest versions of Cookie-parser and Express-session, edit the ‘package.json’ file, add cookie parser & express-session to dependencies with the latest version.

 

Package.json
	{
		  "name": "ExpressApp",
		  "version": "0.0.1",
		  "description": "A Node.js App using express",
		  "dependencies": {
				"express": "~4.0.0",
				"body-parser": "~1.0.1",
				"cookie-parser": "latest",
				"express-session": "latest"
		  },
		  "engine": "node >=0.6.x"
	}

 

Once you edit the JSON file with the required dependencies, install those modules using the following npm command.

 

Install Dependencies
        $ npm install

 

Once you finish the installation, import the installed modules to server configuration file. Then, you can use the functionalities of cookie parser and express-session on your project. The following code is the server configuration with cookie-parser & Express session enabled and used for a user logging system.

 

Server.js
	var express = require('express');
	var bodyParser = require('body-parser'); 

    //import Express-session module and cookie-parser module
	var Session = require('express-session');        
	var cookieParser = require('cookie-parser'); 

	var app = express();

    // To parse every cookies and it must use before expressSession
	app.use(cookieParser());

        
	app.use(Session({secret:'anyStringOfText',
                    saveUnInitialized: true,
                    resave: true }));

	app.use(bodyParser());

    //to render a user form on home page
	app.get('/', function(req, res){
	  var html = '<form action="/" method="post">' +
				 'Your name: <input type="text" name="userName"><br>' +
				 '<button type="submit">Submit</button>' +
				 '</form>';
	  if (req.session.userName) {
		html += '<br>Your username from your session is: ' + req.session.userName;
	  }
	  res.send(html);
	});

	app.post('/', function(req, res){
	  req.session.userName = req.body.userName;
	  res.redirect('/');
	});

	app.listen(80);

The Cookie parser takes 2 arguments: secret and options. the secret is a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. The options an object that is passed.

The Express-session will take 3 arguments, first one is a secret which is a keycode using on cookies. You can use any string of text in this field. The second one is saveUnInitialized which used when you store the sessions to some kind of permanent storage, and it allows a persistent login even if your server is failed. And the last one is resave

The above example is a user logging system which demonstrates Cookie-parser and Express-session modules on Node JS.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...