In this tutorial we will learn how to manage session using node.js and Express 4. For handling session we have express-session plugin module in node.
By using that we can easily maintain session.
Let’s start with installing dependencies and then the code,
Table of Contents
ToggleInstall dependencies
Will going to use following node modules for handling session.
- Express 4
- Express session
I have created a package.json file that will install all required dependencies. have a look,
{
"name": "Express-session-node",
"version": "0.0.1",
"main": "server.js",
"dependencies": {
"express": "^4.8.7",
"express-session": "^1.7.6"
}
}
How to install dependencies?
By typing following command you can install dependencies,
npm install
Express session implementation
List of following functionality we can do using express session,
First will include require node modules and http server.
var app = require('express')();
var http = require('http').Server(app);
var session = require('express-session');
var express = require('express');
app.use(session({
secret: 'test session',
resave: false,
saveUninitialized: true
}));
Set Session :
app.get('/setsession',function(req,res){
sess=req.session;
sess.sessdata = {};
sess.sessdata.email= "inaam";
sess.sessdata.pass= "inaam1234";
var data = {
"Data":""
};
data["Data"] = 'Session set';
res.json(data);
});
In above code you can see that url routing “/setsession” so by hitting this in url functionality works.
So basically start with initializing session by using “req.session”.
and then we are assigning value to session ( i.e : sess.sessdata.email= “inaam” ).
Destroy Session :
app.get('/destroysession',function(req,res){
sess=req.session;
var data = {
"Data":""
};
sess.destroy(function(err) {
if(err){
data["Data"] = 'Error destroying session';
res.json(data);
}else{
data["Data"] = 'Session destroy successfully';
res.json(data);
}
});
});
Here also first we will initialize session and then by using “sess.destroy” we can easily destroy all session variable.
Reload Session :
app.get('/reloadsession',function(req,res){
sess=req.session;
var data = {
"Data":""
};
sess.reload(function(err) {
if(err){
data["Data"] = 'Error Reloading session';
res.json(data);
}else{
data["Data"] = 'Session Reloaded successfully';
res.json(data);
}
})
});
“sess.reload” will reload all session data.
Save Session :
app.get('/savesession',function(req,res){
sess=req.session;
var data = {
"Data":""
};
sess.save(function(err) {
if(err){
data["Data"] = 'Error saving session';
res.json(data);
}else{
data["Data"] = 'Session saved successfully';
res.json(data);
}
})
});
“sess.save” will save session data.
How to run?
First check whether you have installed Node.js or not.
Then install all required dependencies (i.e : express, express-session ) by typing following command in terminal,
npm install
Now, run the server using following command.
node server.js
And now go to browser and hit “localhost:8080”.