Using database to handle Session in Node.js

Session handling is very important and must have thing in any web, without it we won’t be able to track user and it’s activity.So In this article i am going to explain how Use database to handle Session in Node.js. We are going to use express.js.

1.Store session in redis

redis
Redis is an advanced key-value cache and store server.It is a popular technology used in many development environments.Redis is perfect for storing sessions. All operations are performed in memory, and so reads and writes will be fast.Redis gives you a lot of flexibility in how you want to persist session state to your hard-disk.You can read Here for how to install Redis on your server.

we are going to use redis module to save session in redis. Here is the full code of saving
session in redis:

var express = require('express'),
redis = require('redis'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
redisStore = require('connect-redis')(session),
logger = require('morgan'),
bodyParser = require('body-parser');

var client = redis.createClient(),//CREATE REDIS CLIENT
app = express();

app.use(cookieParser('strongsecretcode'));
app.use(session(
{
secret: 'strongsecretcodehere',
store: new redisStore({ host: 'localhost', port: 6379, client: client }),
saveUninitialized: false, // don't create session until something stored,
resave: false // don't save session if unmodified
}
));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var router = express.Router();

router.get('/yoursession/set/:value', function(req, res) {
req.session.user = req.params.value;
res.send('session saved in Redis');
});

app.get('/yoursession/get/', function(req, res) {
if(req.session.user)
res.send(req.session.user);
else
res.send("no session value stored in Redis ");
});

app.use('/', router);
var server = app.listen(2001, function() {
console.log('REDIS SESSION server is listening on port %d', server.address().port);
});

2. Store session in mongodb

Store session in mongodb using node.js
Store session in mongodb

MongoDb is most popular NoSql, a cross-platform document-oriented database.To use MongoDB as the session store we have to install connect-mongo package. Connect-mongo is one of the popular and well tested ExpressJS middleware for storing the sessions.So you can use following code to save session in MongoDB using node.js:

var MongoStore = require('connect-mongo')(session);

//and this is how you can setup express session
app.use(session(
{
secret: 'strongsecretcodehere',
store: new MongoStore({
url:"mongodb://localhost/test",
//other advanced options
}),
saveUninitialized: false, // don't create session until something stored,
resave: false // don't save session if unmodified
}
));

3.Store session in MySQL

Store session in MySQL using Node.js
MySQL is the world’s most popular open source database, enabling the cost-effective delivery of reliable, high-performance and scalable Web-based and embedded database applications, including all five of the top five websites. To use MySQL as the store we have to install express-mysql-session package.So you can use following code to save session in MySQL using node.js:

var SessionStore = require('express-mysql-session');

var options = {
host: 'localhost',
port: 3306,
user: 'root',
password: 'password',
database: 'sessions'
};

var sessionStore = new SessionStore(options);

//and this is how you can setup express session
app.use(session(
{
secret: 'strongsecretcodehere',
store:sessionStore,
saveUninitialized: false, // don't create session until something stored,
resave: false // don't save session if unmodified
}
));

Add a Comment

Your email address will not be published. Required fields are marked *