jordan
jordan

Reputation: 10812

Using subdomains locally on an express app

I have node app running on express. I'd like to set up two different account types (one for buyers, one for sellers) and have them accessible through different subdomains (ie buyers.example.com and sellers.example.com). I'm not sure how to set this up locally. I know that I can edit the hosts file on my machine to have *.localhost resolve to 127.0.0.1, but that doesn't solve my problem. In that case, buyers.localhost/login and sellers.localhost/login will route to the same place. Is this a common issue, and if so, what is the standard way of handling this? What are some options for me to separate the logic for handling two account types?

Upvotes: 2

Views: 2259

Answers (2)

Chukwuemeka Maduekwe
Chukwuemeka Maduekwe

Reputation: 8586

app.all("*", function (req: Request, res: Response, next: NextFunction) {
  if (req.headers.host == `v1.${process.env.SERVER_DOMAIN}`) req.url = `/v1${req.url}`; // ? <= direct from v1 to domain/v1
  if (req.headers.host == `api.${process.env.SERVER_DOMAIN}`) req.url = `/api${req.url}`; // ?  <= direct from v1 to domain/api

  next();
}); //Port is important if the url has it

Upvotes: 0

andresgottlieb
andresgottlieb

Reputation: 950

First add this:

app.get('*', function(req, res, next){
    if (req.headers.host == 'buyers.localhost:5000') { //Port is important if the url has it
        req.url = '/buyers' + req.url;
    }
    else if(req.headers.host == 'sellers.localhost:5000') {
        req.url = '/sellers' + req.url;
    }  
    next();
});

And then:

app.get('/login', function(){
  //Default case, no subdomain
})

app.get('/buyers/login', function(){
   //Buyers subdomain
})

app.get('/sellers/login', function(){
   //Sellers subdomain
})

Learned this here: https://groups.google.com/forum/#!topic/express-js/sEu66n8Oju0

Upvotes: 4

Related Questions