Kunto Handoko
Kunto Handoko

Reputation: 79

create dynamic subdomains on express js and node js

I'm trying to make a website where when a user register, then he will have the url > username.mydomain.com, I have tried a variety of ways, ranging from vcap.me, etc., well how to create dynamic subdomains such as a simple and easy,

Upvotes: 1

Views: 942

Answers (1)

Techhead Ritz
Techhead Ritz

Reputation: 151

// Use below code to get your subdomain name
// get your dynamic subdomain

app.use((req, res, next) => {
  if (!req.subdomains.length || req.subdomains.slice(-1)[0] === 'www') return next();
  // otherwise we have subdomain here
  var subdomain = req.subdomains.slice(-1)[0];
  // keep it
  req.subdomain = subdomain;
  next();
});


// conditional render a page
app.get('/', (req, res) => {
  // no subdomain
  if (!req.subdomain) {
    // render home page
    // mydomain.com
    res.render('home');
  } else {
    // render subdomain specific page
    // mypage.mydomain.com
    res.render('mypage');
  } // you can extend this else logic to render the different subdomain specific page
});


Note: to test this locally. you can use Nginx reverse proxy to forward your test url req to your local server and do not forget to point your test url to your local host 127.0.0.1 in your hosts file of your machine

Upvotes: 1

Related Questions