I'm currently serving static files like this:
app.use('/javascripts', express.static(join(__dirname + '/assets/javascripts')));
and it works as expected.
What I would like to do is to use the user session to serve static files depending on the session. I've tried this:
app.use('/javascripts', (req: Request, res: Response, next) =>{
if(req.session.auth){
express.static(join(__dirname + '/auth/javascripts'))
} else{
express.static(join(__dirname + '/assets/javascripts'))
}
});
but it doesn't serve the files. Can someone explain why it doesn't work and how I can achieve what I'm trying to do?
A middleware function (the second argument of .use()
) should process the request and call next()
, so this code does nothing.
What you need is to just have a dynamic route (instead of middleware) that redirects to the correct static directory according to req.session.auth
:
app.get('/javascripts/*', function(req, res){
if(req.session.auth){
res.sendfile(req.params[0], {root: './auth/javascripts'});
} else {
res.sendfile(req.params[0], {root: './assets/javascripts'});
}
});