2

I'm using PassportJS to secure a WebApp (written with AngularJS). I'm using NodeJS with Express (4.0.0) to serve static content after the login-screen. I don't get how to use a middleware along with express.static() at the same time.

My (not working) code looks like

app.use('/secure', 
    function (req, res, next) {
        if (req.isAuthenticated())
            return next();

        res.redirect('/');
    }, 
    express.static(__dirname + '/../../client'));

The plan is, that the middleware ensures, that the user is only forwareded to the WebApp if he/she is logged in. If not, he/she/it is redirected to the root folder.

I found this answer, but according to the documentation, the new version supports multiple functions. This isn't the "clean" solution I'm looking for, since the directory contains too many subfolders and files.

Thanks in advance

Community
  • 1
  • 1
Boern
  • 7,233
  • 5
  • 55
  • 86

1 Answers1

1

When you attach middlewares to the same route they get executed in the same order of declaration, so if you want to execute any middleware before express.static, all what you have to do is attach it to the same route and declare it before.

app.use('/secure', myMiddleWare);
app.use('/secure', express.static(__dirname + '/../../client'));
teleaziz
  • 2,220
  • 1
  • 19
  • 25