Search code examples
node.jssession-cookies

Sessions in Node.js


I'm very new to Node.js and I can't seem to find a way to store sessions, or at least not a official way.

I read you can do it with Redis I found that express has it's own Session handler and I found a Git repository.

Now I don't know which method to use... I'm from a PHP background where it was really easy to do this.

I would prefer not to install any more modules. I am currently using Express.js, so is there a detailed guide to Express.js' session handler?


Solution

  • First of all, you need to use the proper middleware or include it when you are setting up your Express.js application.

    app.use(express.cookieParser());
    app.use(express.session({secret: 'this is the secret'}));
    

    or

    express --sessions myapp
    

    Both the cookieParser and sessions middleware are required also; the order matters.

    After you include the required middleware, a sessions object is added to every request and you can set and get properties on the object.

    Setting:

    app.get('/', function(req, res) {
      req.session.user = 'mike';
      res.send('index');
    });
    

    Getting:

    app.get('/about', function(req, res) {
      var user = req.session.user;
      res.send("I know you, you're" + user + '!');
    });