Protecting a Static File Server with ExpressJS

I have implemented an authentication system based on this guide using express.js and passport.js.

In the past, I used an express server with modRewrite, which looked like this:

var express    = require('express');
var modRewrite = require('connect-modrewrite');

var app = express();
var baseURL = './dev/';
var portnum = 3000;

app.use(modRewrite([
  '^[^\\.]*$ /index.html [L]'
]))
.use(express.static(baseURL))
app.listen(process.env.PORT || portnum)

But now, using authentication, I use this route:

var baseURL = './dev/';

router.get('*', isAuthenticated, function(req, res, next){

    // if path contains file extension
    // behave as static file server
    if (req.path.indexOf('.') !== -1) {

        var fullPath = baseURL + req.path;
        res.sendfile(fullPath)

    // else send index.html
    } else {

        res.sendfile(baseURL + '/index.html')

    }

});

I think there is a better way to do what I'm trying to do, and I would like to use the express.static server as well as modRewrite. Also, my authenticated server is much slower, probably because it needs to authenticate every time a file is requested. Any tips on how to make this faster?

+4
source share
1

( JWT ).

app.use(function (req, res, next) {
    if(isAuthenticated()) {
       next();
    } else {
       res.send(401, 'unauthorized');
    }
});
0

All Articles