clarkk
clarkk

Reputation: 27689

Express and subdomains (no static files)

What is the best practice to handle subdomains with nodejs and express?

Each subsomain will not be static files like index.html etc. but pure code and logic

var express = require('express'),
    http = require('http');

var app = express();
app.set('port', 8080);
app.set('case sensitive routing', true);

// Catch api.localhost
app.get('/*', function(request, response){
    /*
        Other logic
    */
    response.end('API');
});

// Catch www.localhost
app.get('/*', function(request, response){
    /*
        Other logic
    */
    response.end('WEB');
});

http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port '+app.get('port'));
});

Upvotes: 1

Views: 449

Answers (1)

bryanmac
bryanmac

Reputation: 39296

One option is to have two different node apps running.

If you want it in the same node app, you won't be able to have multiple /* routes. Only the first one would get hit. One good option is to put a reverse proxy in front of it and route the domain name back to the node app with a path. That has other benefits like on linux not having your port 80 apps run under sudo

For example, in node-http-proxy, they added the ability to route the proxy by path:

var options = {
  router: {
    'api.myhost.com': '127.0.0.1:8080/api',
    'myhost.com': '127.0.0.1:8080',
    'www.myhost.com': '127.0.0.1:8080'
  }
};

Then in your node app running on 8080 would have routes:

'/api/*' --> api code
'/*' --> web 

nginx is another reverse proxy option.

I would probably just run two different node processes for front and backend and hide it behind the proxy. Keeps the code for each clean and allows you to scale and configure them independently without code changes.

var options = {
  router: {
    'api.myhost.com': '127.0.0.1:8080',  // note different app on diff port
    'myhost.com': '127.0.0.1:8090',
    'www.myhost.com': '127.0.0.1:8090'
  }
};

Here is a good intro.

Upvotes: 2

Related Questions