How to create subdomain for user in node.js

All we need is an easy explanation of the problem, so here it is.

I’d like to share some user information at username.domain.com at my application. Subdomain should be available after user create his account.

I have found nice module that could be useful in that case: Express Subdomain

How can I do it properly using that module? Maybe this module isn’t so useful so which one should I use?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

As I mentioned in OP comments, using Nginx webserver in front of Node would be very good option, since this is a secure way to listen 80 port. You can also serve static files (scripts, styles, images, fonts, etc.) more efficiently, as well as have multiple sites within a single server, with Nginx.

As for your question, with Nginx, you can listen both example.com and all its subdomains, and then pass subdomain to Node as a custom request header (X-Subdomain).

example.com.conf:

server {
    listen          *:80;
    server_name     example.com   *.example.com;

    set $subdomain "";
    if ($host ~ ^(.*)\.example\.com$) {
        set $subdomain $1;
    }

    location / {
        proxy_pass          http://127.0.0.1:3000;
        proxy_set_header    X-Subdomain     $subdomain;
    }
}

app.js:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.end('Subdomain: ' + req.headers['x-subdomain']);
});

app.listen(3000);

This is a brief example of using Nginx and Node together. You can see more detailed example with explanation here.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply