Venkatesh A
Venkatesh A

Reputation: 2474

Securing assets folder in express js node

I have an assets folder in which i have images and render them with node express js. Is there a way to secure the assets in such a way that the users access only the assets entitled to them?

const app = express();
app.use('/assets', express.static('assets'));
app.listen(port, () => {
    console.log(`Server runnning on port ${port}`);
});

Upvotes: 0

Views: 1130

Answers (1)

indiPy
indiPy

Reputation: 8062

Basically you are looking for authorization middleware which will take care of checking the access.

You can use passport js or any other library or create your own.

Since you are using Express to code, this snippet may be useful.

        requireLogin = (req, res, next) => {
        if (!req.user) {
            return res.status(401).send({ error: 'You must login!' });
        }
        next();  
 }; 
     app.get('/assets',requireLogin , express.static('assets'));

Express has very good documentation on middleware here .

Upvotes: 1

Related Questions