How do I generate a session ID in Node.js?

user3658794 picture user3658794 · Oct 14, 2014 · Viewed 8.8k times · Source

Im trying to learn Node.js without using any third party modules or frameworks. I'm getting to the point where I got to figure out how to give session ids to users who login...

So far I know I can set the session id by writing it in the headers, setting the cookies:

writeHead(200, {'set-cookie':'Math.random() ' } );

and then I can retrieve the session id and later compare it to the database.

request.headers.cookie(request.url);

But how do I GENERATE the session ID value? I am new to programming. The first thing I thought of was using Javascript's Math.random(); and using that value to set the cookie ( session id ). In my mind it feels stupid but that is how far I can think.

How am I suppose to generate the session id using Node.js, no third party modules, barebones please!

Answer

Tracker1 picture Tracker1 · Oct 14, 2014

Note: You should probably use a session manager for whatever framework you go with.. be it connect, express, koa or any number of others.


This will give you a UUID version 4 (random) using crypto.randomBytes.

var crypto = require('crypto');
module.exports = genUuid;

function genUuid(callback) {
  if (typeof(callback) !== 'function') {
    return uuidFromBytes(crypto.randomBytes(16));
  }

  crypto.randomBytes(16, function(err, rnd) {
    if (err) return callback(err);
    callback(null, uuidFromBytes(rnd));
  });
}

function uuidFromBytes(rnd) {
  rnd[6] = (rnd[6] & 0x0f) | 0x40;
  rnd[8] = (rnd[8] & 0x3f) | 0x80;
  rnd = rnd.toString('hex').match(/(.{8})(.{4})(.{4})(.{4})(.{12})/);
  rnd.shift();
  return rnd.join('-');
}

You could also use the UUID module from npm. The crypto package is not an in-browser option, though you could use Browserify's crypto shim.