Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting access to static files in ExpressJS

I have a server that routes pretty much everything through middleware to check to see if you're logged in, but that only works for routes. I would also like it to work with static files in the public directory. How would I go about doing that?

update: it's better to not worry about protecting what's in the /public folder because express offers a res.download(...) feature. Example on the Express.JS GitHub page

like image 779
Stephen Avatar asked Apr 16 '11 00:04

Stephen


1 Answers

To clarify static files are also server by express using the express.static middleware. In theory you can include middleware before it to handle the security. Besides the idea of the static middleware is that you only make the folder public statically available since its public.

You can find static defined here. You can either rewrite it to allow you to inject middleware into it.

Or you can just write a naive static file router yourself.

Have you tried injecting your own security log in middleware before your static middleware.

app.use(security);
app.use(express.static(dirname + '/public'));
like image 192
Raynos Avatar answered Oct 18 '22 03:10

Raynos