Working with Sessions in Express.js

Express has nice examples in the github repo. One of them deals with authentication and shows how to attach the user to the req.session object. This is done inside the app.post('/login') route.

To limit access to certain pages add a simple middleware to those routes

function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error="Access denied!";
    res.redirect('/login');
  }
}

app.get('/restricted', restrict, function(req, res){
  res.send('Wahoo! restricted area, click to <a href="https://stackoverflow.com/logout">logout</a>');
});

As Brandon already mentioned you shouldn’t use the MemoryStore in production. Redis is a good alternative. Use connect-redis to access the db. An example config looks like this

var RedisStore = require('connect-redis')(express);

// add this to your app.configure
app.use(express.session({
  secret: "kqsdjfmlksdhfhzirzeoibrzecrbzuzefcuercazeafxzeokwdfzeijfxcerig",
  store: new RedisStore({ host: 'localhost', port: 3000, client: redis })
}));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)