Two static directories (public+private) in node.js Express framework

The idea is the follow:

  • Send the login directory when the user is not authenticated.
  • Send the app directory one time that the user logs in (in this case, using passport module).

Example:

Not logged:

request: GET /

response: index.html from PATH_login

Logged:

request: GET /

response: index.html from PATH_app

I tried this but it didn't work:

app.use(function(req,res,next){

    if ( req.isAuthenticated() )
    {
        // user is authenticated
        return express.static(PATH_app)
    }
    else
    {
        // user is not authenticated
        return express.static(PATH_login)
    }

});

On initialization, you're setting that the middleware function that does the switching should be called for every request.

You should also initialize each of the middleware functions that would be switched between at this time.

At runtime for each request (when the code in the function you pass to app.use gets run), for that switching function to forward to the appropriate middleware, it would call the relevant function:

var appStatic = express.static(PATH_app);
var loginStatic = express.static(PATH_login);

app.use(function(req, res, next) {
    if (req.isAuthenticated()) {
        // user is authenticated
        return appStatic(req, res, next);
    } else {
        // user is not authenticated
        return loginStatic(req, res, next);
    }
});