Jo Colina Jo Colina - 1 year ago 81
Node.js Question

Add an exception to ExpressJS app.use()

I'm working on a NodeJS project, and using Express as my routing framework.

I have a register form in my site, and a login form, both of which send requests to

respectively). However, I would like to be able to have
as routes to see profiles of different users, but of course, this routes imply that I have a session_id for every logged in user.

My question is, how can I use
app.use('/users', checkForSessionId)
, without applying it to register and login?

Answer Source

This is where you need to use middleware


var users = require('./routes/user');
app.use('/users', users);


var express = require('express');
var router = express.Router();
function checkForSessionId(req, res, next){
    //if no valid session
    //    return res.status(401).json("not authorised");

router.get('/:userId', checkForSessionId, function(req, res){
    //this is a route which requires authentication
})'/register', function(req, res){
    //authentication is not necessary

module.exports = router;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download