Leonardo Cavazzani
Leonardo Cavazzani

Reputation: 293

Dynamic express.static() folder path

I have an application that uses express.static to access some user information, and the routes logic are like this:

app.get('/principal',function(req,res,next){
    if(req.query.user=='admin'){
        next();
    }else{
        res.send("not allowed");
    }
});
app.use('/principal',express.static('/_site'));

But now I need it to all users, so should be something like that:

 var username = '';
 app.get('/principal',function(req,res,next){
        if(req.query.user){
            username = req.query.user;
            next();
        }else{
            res.send("not allowed");
        }
    });
    app.use('/principal',express.static(username+'/_site'));

I have a folder to every username, my express.static() keeps reading the username var empty.

Upvotes: 3

Views: 2506

Answers (2)

YouneL
YouneL

Reputation: 8361

Try to serve static files from the route handler to make it dynamic to the query username:

app.get('/principal',function(req,res,next){
    if(req.query.user){

        // serve static files for usename
        app.use('/principal', express.static(username +'/_site'));

        res.send("allowed");
    }else{
        res.send("not allowed");
    }
});

Upvotes: 4

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

I don't think you can do that with express.static. However, you could,

app.get('/principal', function(req, res){
    if(req.query.user){
        const username = req.query.user;
        const path = `${username}/boo.js`
        res.sendfile(path, {root: '/_site'});
    }else{
        res.send("not allowed");
    }
});

Upvotes: 0

Related Questions