node package manager


Manage sessions for http.ServerRequest using various storage engines

Session Handling for NodeJS' HTTP Server

session-manager provides a session management layer around node's built in http server using cookies.

This example builds on Node's example web server, and responds with an incrementing count, per user.

var http = require('http');
var sessionManager = require('./session-manager.js');
// Best to use one shared session manager across requests 
var sessionManager = sessionManager.create({engine: 'memory'});
// Usage with Node's HTTP Server 
http.createServer(function (req, res) {
    if (req.url == '/') {
        // Load session for this user 
        var session = sessionManager.start(req, res);
        session.set('count', (session.get('count') || 0) + 1);
    // Display count 
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end((session ? session.get('count') : '') + '\n');
}).listen(1337, "");
console.log('Server running at');

It supports various (and extensible) data storage engines. Currently included ones are:

  • file (stores data on disk)
  • memory (keeps data in array, useful for development, as restarting node will reset values)

It is simple to create a new storage engine, e.g. redis by creating an object with two function keys, set(session_id, key, val) and get(session_id, key). The simplest example to base this on is the memory engine (./engines/memory.js).