Yaron Dassonneville
Yaron Dassonneville

Reputation: 951

How to create sessions in Node.js

In Node.js / MongoDB I want to create an easy session and give it to another page so I can know if a user is logged in or not. I want to know if he/she can access the page or not. How can I do this?

How do I set a session and how do I get the value to check if I have to redirect the user?

Upvotes: 1

Views: 2912

Answers (1)

Benjamin Albert
Benjamin Albert

Reputation: 748

Use Express.js session.

It's also worth taking a look at Passport.js which makes implementing authentication in Node.js really easy.

Express.js session example:

var express = require('express');
var session = require('express-session');
var app = express();

// Make sure this is defined before any of your routes
// that make use of the session.
app.use(session({
  secret: 'keyboard cat',
  cookie: { maxAge: 60000 },
  resave: false,
  saveUninitialized: false
}));

// Access the session as req.session
app.get('/login', function(req, res) {
  req.session.user = 1;
  res.end('User 1 is logged in, please go to the /discussion page.');
});

app.get('/discussion', function(req, res) {
  var sess = req.session;
  if (typeof sess.user === 'undefined') {
     res.redirect('/login');
  } else {
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>user: ' + sess.user + '</p>');
    res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
    res.end();
  }
});

Upvotes: 1

Related Questions