Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic subdomains for each user using node express?

On signup, I want to give user his profile and application at username.example.com I have already created wild-card dns at my domain provider website.

How can I do that?

like image 359
user2513942 Avatar asked Mar 11 '14 07:03

user2513942


People also ask

How do you manage subdomains?

To add or edit a subdomain Choose your app that you want to manage subdomains for. In the navigation pane, choose App Settings, and then choose Domain management. On the Domain management page, choose Manage subdomains. In Edit domain, you can edit your existing subdomains as needed.


2 Answers

If using Node.js with Express.js, then:

router.get('/', function (req, res) { 
    var domain = req.get('host').match(/\w+/); // e.g., host: "subdomain.website.com"
    if (domain)
       var subdomain = domain[0]; // Use "subdomain"
    ...
});
like image 181
eddie Avatar answered Sep 24 '22 10:09

eddie


I got here because I wanted to do exactly what OP asked:

On signup, I want to give user his profile and application at username.example.com

The previous answers are ways to handle incoming requests from the already provisioned subdomains. However, the answers led me to thinking what I want is actually really straightforward - here goes:

// Creating the subdomain

app.post('/signup', (req, res) => {
  const { username } = req.body;

  //... do some validations / verifications
  // e.g. uniqueness check etc

  res.redirect(`https://${username}.${req.hostname}`);
})

// Handling requests from the subdomains: 2 steps
// Step 1: forward the request to other internal routes e.g. with patterns like `/subdomain/:subdomain_name/whatever-path`

app.use((req, res, next) {

  // if subdomains
  if (req.subdomains.length) {

    // this is trivial, you should filtering out things like `www`, `app` or anything that your app already uses.

    const subdomain = req.subdomains.join('.');

    // forward to internal url by reconstructing req.url

    req.url = `/subdomains/${subdomain}${req.url}`
  }
  return next()
});

// Handling requests from the subdomains: 2 steps
// Step 2: Have router setup for handling such routes
// you must have created the subdomainRoutes somewhere else

app.use('/subdomains/:subdomain', subdomainRoutes)

Hope it helps.

like image 30
flash Avatar answered Sep 25 '22 10:09

flash