node.jsroutespublic-folders

How to block routing to a page in the public folder


I'm trying to design my NodeJS application, but there is something I am confused about.

In my application, I plan to put all of the frontend material in the folder /public and then put the line

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

in my app.js file.

So with this in place, the user will be able to go to thesite.com/gallery/stuff and it will work because the gallery folder is in /public.

But what if I don't want the user to be able to visit this area? How can I intercept his request and make sure he is logged in, for example? Is there a way to make some parts of the public folder not so public?


Solution

  • You can put a router right before it

    app.all('/gallery/*', function(req, res, next){
        if(!req.user) next(new Error('You shall not pass!'));
        else next();
    });
    app.use(express.static(__dirname + '/public'));