Search code examples
node.jsexpresscookie-session

Generating unique sessionId with Express Cookie-Session


I'm using node/express.js with cookie-session's in my application and am trying to understand the proper way create a unique ID for each session.

Currently, when a user logs in a cookie is stored in their browser with a value, for example: session: ABC123. If the user logs out, the cookie is deleted. When the user logs back in, the same cookie and value are stored in the browser session: ABC123.

Ideally, I would like to randomize the session value so I can count the number of unique sessions this user has created. I'm wondering if there is a way to randomize the cookie-session value on every login -- or, should I be creating a separate cookie that stores a random value for this purpose?

Thanks!


Solution

  • Generating a unique identifier? That sounds like a job for universally unique identifiers- UUIDs! There's a lovely little Node.js package called uuid that can handle the logic behind them for you. Here's how you might use it to set a unique cookie in an ExpressJS application:

    const express = require('express');
    const uuid    = require('uuid/v4');
    
    const app = express();
    
    app.get('/', (req, res) => {
      if (req.cookie.id) {
        return res.end(`Welcome back, ${req.cookie.id}!`);
      }
    
      const id = uuid();
    
      res.cookie('id', id, { httpOnly: true });
      res.end(`Welcome, ${id}!`);
    });
    
    app.listen(3000);
    

    Your exact usage will probably be a little different, since you'd only need to generate a new UUID when somebody logs in, but the principles are the same.

    P.S. - Have you considered the express-session package for identifying individual users of your application?