Restricting route access with Express

Wed Jul 04 2012

A simple way to require admin access, or perform any other action, on a subset of routes with Express.

This will send you along to the requested route if your session is set, otherwise it will redirect to your login page. Remember to place this before all other routes it must override.

app.all('/admin*', function(req, res, next){
  if(req.session.admin) next();
  else res.redirect('/login');
});

An example of routes it will match.

app.get('/admin');
app.get('/admin/:id');
app.post('/admin/edit/:id');