5

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.

surenyonjan
  • 1,989
  • 2
  • 15
  • 25
  • Similar question was responsed widely here: https://stackoverflow.com/questions/36875701/nodejs-express-global-unique-request-id/47261545#47261545 – David Vicente Feb 13 '18 at 15:49
  • @DavidVicente That question/answer is not the same as the one asked here. This question refers to Session middleware and management, not request tracking – SteveLacy Jan 16 '19 at 18:51

1 Answers1

2

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.

Rohit Choudhary
  • 2,191
  • 1
  • 21
  • 33
  • 1
    Hey! I stumbled upon this answer and got interested of why does the latter version of genid function create ids that avoid collision? Can you open that up a little? What's all that about? :) – zaplec Apr 29 '20 at 15:33