Ben Diamant Ben Diamant - 2 years ago 122
Node.js Question

NodeJS and Express: Add auth middleware to static path

I have a node app running express as the web app framework and I use Stormpath for authentication.

Storm path gives the ability to protect a route with several middlewares,
for example:

router.get('/user_data_api', stormpath.apiAuthenticationRequired, function(req, res) {
res.send('hello you are authenticated!");

What I want to do is to add authenticationRequired as a middleware to the static definition of express:

app.use(express.static(__dirname + '/public'));

This could be achieved by adding a route to the static assets, so if I have a file ./public/index.html I can set the route like this:

stormpath.auth_fn, express.static(__dirname + '/public'));

But then the file will be in

And I want it in


Answer Source

Do just:

app.use(stormpath.auth_fn, express.static(__dirname + '/public'));

It'll add stormpath.auth_fn and express.static(__dirname + '/public') middlewares to the / path and, hence, will protect every route.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download