I am Hack Sparrow
Captain of the Internets.

Sessions in Express.js (Node.js Web Framework)

Session management in Node.js Express

For a more elaborate and updated tutorial on sessions in Express, visit http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/.

Wondering if Node.js Web servers supports sessions? It is a breeze if you use the Express.js Web framework. I will guide you through the process of installing Express and doing a sample code for handling sessions in Node.js.

First off, install Express:

$ npm install express -g

Then, create an app with sessions support:

$ express --sessions

The session object is attached to the HTTP request object, just read from it or write to it. Here is an example of handling session in Express:

app.post('/', function(req, res) {
if (req.session.logged) res.send('Welcome back!');
else {
req.session.logged = true;
res.send('Welcome!');
}
};

In the development mode, Express.js uses MemoryStore for session management which is just an ad-hoc session store. However, on your production server, you will need to switch to a more efficient session store. I recommend RedisStore for it. Read here how to integrate RedisStore to your Node.js Express app.

17 Responses to “Sessions in Express.js (Node.js Web Framework)”

  1. Jorge says:

    I’m new in node js, my question is
    Is global.session safe to use?

  2. Captain says:

    Jorge, it can be safe or unsafe depending on what you are trying to accomplish. Having said that, you might want to read this http://www.hacksparrow.com/global-variables-in-node-js.html to know about other options for creating global variables in Node.

  3. Maddox says:

    But wouldn’t a session write in the global scope potentially conflict with parallel requests?

  4. Captain says:

    Maddox, it might, so it is not reliable at all. The recommended method would be to pass the session object of the request to the function which would process the session data.

  5. Henrik says:

    How can I set the max age of the session?

    What I would like to accomplish is a “Remember me” functionality.

  6. Captain says:

    @Henrik app.use(express.session({cookie: {maxAge: 1000000000000}}));

  7. Pravin says:

    I am new for node js I need help to understand redis ,session and express…
    How we can create session id in redis. and store session information in cache so that next login time it will keep track for that user.
    please share simple code like login and logout using redis express and session if possible ,please

Make a Comment