Skip to content
walterd edited this page May 30, 2012 · 1 revision

Brief overview of sessions in node.js

Options

There are 3 main options for Session Support

Sessions with Memory Store

By default, express stores session info in memory

http://expressjs.com/guide.html#session-support

Sessions with Disk Store

There are also modules which allow session info to be stored in the DB

MongoDB - https://github.com/mikkel/express-session-mongo

Redis - https://github.com/visionmedia/connect-redis

Don't Use Sessions

Somes sites suggestion trying to use sessions as little as possible and use client-side storage for performance reasons. See point #7 here:

http://engineering.linkedin.com/nodejs/blazing-fast-nodejs-10-performance-tips-linkedin-mobile

Setup

Memory Store

  1. Add use's to app.js file:
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));

Obviously "keyboard cat" needs to be a random secret string key.

Disk Store (MongoDB)

  1. Install the module

npm install express-session-mongo

  1. Add dependencies

MongoStore = require('express-session-mongo');

  1. Pass instantiated MongoStore instance to the session plugin.

app.use(express.session({ secret: "keyboard cat", store: new MongoStore() }));

Usage

The session data is available in all routes. Properties on req.session are automatically saved on a response.

The example on the express page is:

app.post('/add-to-cart', function(req, res){
  // Perhaps we posted several items with a form
  // (use the bodyParser() middleware for this)
  var items = req.body.items;
  req.session.items = items;
  res.redirect('back');
});

Therefore, it's pretty easy to have a user log in and set a session variable indicating the status. Though I'm sure this isn't the best for security reasons.

Clone this wiki locally