Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set express.static directory dynamically

I want to set root directory of exress.static in a way that request from a subdomain will have separate root folder.

I have a site with multiple subdomain, and the structure is a following

index.js
public/
-- site1
-- site2
-- site3

i want to set public/site1 as static folder when request is from site1.mydomain.com and site2.mydomain.com should not be able to get files from public/site1 directory.

I have tried this:

app.use ((req, res, next) => {
  let hostName = req.headers.host;
  let options = domainMap[hostName];

  req.app.use (
    express.static (path.join (__dirname, 'public', options.publicDir))
  );

  next ();
});

domainMap holds the following object:

{
    site1:{
         publicDir:'site1',
    },
    site2:{
         publicDir:'site2',
    },
    site3:{
         publicDir:'site3',
    }
}

what it does now is it sets the public directory only for the first request, but is there any way to change i dynamically for every request ?

like image 967
Imtiaz Chowdhury Avatar asked Oct 26 '25 05:10

Imtiaz Chowdhury


1 Answers

You can generate the desired middleware function dynamically and then call it manually. You don't want to register it with app.use() because then it will be active for all requests. That's why you need to call it manually. Also, express.static() generates a middleware that already calls next() so you don't need to do that either except in cases where you don't call the generated middleware.

app.use ((req, res, next) => {
  let hostName = req.headers.host;
  let options = domainMap[hostName];
  // protect against missing or unexpected hostName
  if (options && options.publicDir) {
      let middleware = express.static(path.join (__dirname, 'public', options.publicDir));
      middleware(req, res, next);
  } else {
      // nothing to do here, keep routing
      next();
  }
});
like image 51
jfriend00 Avatar answered Oct 28 '25 19:10

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!