Jamie Jordan Jamie Jordan - 6 months ago 10
Node.js Question

stacking of routes in node.js

var express = require('express');
var router = express.Router();
router.use(function(req, res, next){
console.log(req.user)
if(!req.user){
res.redirect('/login');
}else{
res.locals.username = req.user.username;
return next();
}
});

//this won't work
router.get('/register', function(req, res, next) {
res.render('register');
});


The first block make sense and it's working,I able to have a login system with protected routes. But in the same time it ruined my second bit, it will show the login page althought I try to nagivate to localhost:3000/register.

Answer

When you're using router.use() you're telling the router to use that function middleware in all the next roter.get() routes. So here, the order makes sense. If you care about order you can do what @bloodyKnuckles do. Or if you want to keep that pattern for your routes you can do the following :

// Routes that don't need authorization like register
router.get('home',...);
router.get('register',...);

// Use your authorization middleware
router.use(function(req, res, next){
  console.log(req.user)
  if(!req.user){
    res.redirect('/login');
  }else {
    res.locals.username = req.user.username;
    return next();
  }
});

// At this point you're using the authorization middleware. 
// Any routes declared from here will call authorization middleware before its handler.
router.get('profile', ...);
Comments