How to generate custom session id with express-session?

surenyonjan picture surenyonjan · Jul 31, 2015 · Viewed 9.1k times · Source

I am using Redis as session store and I would also like to create custom session id with express-session. So far I achieved was creating session with constant string like this:

redis configuration

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var session = require('express-session');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);

var routes = require('./routes/index');
var api = require('./routes/api');

var app = express();
var client = redis.createClient();

// compress all requests
app.use(compression())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'SECRET',
  resave: false,
  saveUninitialized: false,
  store: new RedisStore({ host: 'localhost', port: 6379, client: client}),
  cookie: {
    maxAge: 60000
  },
  genid: function(req) {
    return "myApiKey";
  }
}));
app.use('/', routes);
app.use('/request_api', api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

which creates keys in redis like below:

127.0.0.1:6379> keys *
1) "sess:myApiKey"

However, I could not generate unique id with uuid as mentioned in doc here session-store github. I have tried inserting session value in my index routes file (routes/index.js) like this

/* GET home page. */
router.get('/', function(req, res, next) {
  req.session.user = "12345";
  res.render('index', { title: 'MyApp' });
});

But could not read value inside genid function due to value undefined. So, my question is:

Can I generate session id with uuid of any model like user->uuid? If yes, how can I do it?

Thanks, any help will be appreciated.

Answer

Rohit Choudhary picture Rohit Choudhary · Jan 27, 2016

You can do like this.

   var crypto = require('crypto');
   var uuid = require('node-uuid');

You need to require node-uuid and then in genid function

genid:function(req){
     return uuid.v1();
},

or to avoid id collision

 genid:function(req){
     return crypto.createHash('sha256').update(uuid.v1()).update(crypto.randomBytes(256)).digest("hex");
 },

You can access session id anywhere in the application by req.sessionID.