Skip to content Skip to sidebar Skip to footer

Session Management In Nodejs

I am beginner of NodeJS.And just started a simple project where I need a session management concept. So How to manage the session in NodeJS application. In my project there is two

Solution 1:

For the session management we need a middleware 'cookie-parser'.Previously it is the part of express but after express 4.0 and later it is a separate module.

So to access the cookie parser we need to install in our project as :

npm install cookie-parser --save

Then add this into your app.js file as :

var cookieParser = require('cookie-parser');

 app.use(cookieParser()); 

Then we reqired session module. So first of all install the session module by :

npm install express-session --save

Then to enable the session. we add below code in app.js file.

app.use(session({secret:config.sessionSecret, saveUninitialized : true, resave : true}));

Then come to the routes.js file :-

Let us suppose there is a session variable favColor. Now using session set the color and get in the other page. the code is look like :-

router.get('/setColor', function(req , res , next){
        req.session.favColor = 'Red';
        res.send('Setting favourite color ...!');
    });
    
    router.get('/getColor', function(req , res , next){
        res.send('Favourite Color : ' + (req.session.favColor == undefined?"NOT FOUND":req.session.favColor));
    });

This is all about the session management.We can also learn more about the session :- This Reference

Solution 2:

I dont suggest you try to build your own session and use https://github.com/expressjs/session instead which works with express well.

Solution 3:

An update on 2019, using express-session 1.15.6 (From 1.5 there's no need to use cookie-parser, session can read and write the cookie directly.)

In app.js:

const app = express()
const session = require('express-session');
const options = {
  name: 'foo', // Default is connect.sidstore: this.store, // Default is memoryStore, which is for dev only. Setup redis or memcached for prodsecret: 'bar', // Required, used to sign session id cookiesaveUninitialized: true, // Forces a session that is "uninitialized" to be saved to the storeresave: false, //Forces the session to be saved back to the session storerolling: true//Force a session identifier cookie to be set on every response
};
// Session method will return a middleware function.const middleware = session(options);
// Now we can make use of session in all the requests
app.use(middleware)

In routes.js or in any handler file created for specific route:

handler1(req, res, next) {
  req.session.someField = 'foo';
  // Use save method to update the store immediately, if there's other AJAX call pending. 
  req.session.save();
}

handler2(req, res, next) {
  console.log(req.session.someField); 
}

handler3(req, res, next) {
  // we use delete operator here.delete req.session.someField; 
}

Post a Comment for "Session Management In Nodejs"