Writing Modular Web Apps

If you want to write a web app that is easy to share with others, consider writing it as a module instead of as an app. This way, users who want to run a web server on one port with multiple apps can run your web app within a virtual host:

var vendorApp = modules.vendor(config.vendor),
    mainApp = modules.main(config.main);

modules.http.serve({port: config.port}, function() {
  var args = [];

  switch (request.headers.Host) {
    case '':
      return vendorApp.apply(null, args);
      return mainApp.apply(null, args);

The app shown above is a basic virtual host implementation, which is the most common way of running a multi-tenant web server. It simply routes requests to a web app based on the HTTP Host header. The web app module (modules.vendor or modules.main above) would then look something like this:

function(config) {
  return function(request, response) {
    switch (request.path) {
      case '/':
        return response.end('Hello World');
        return response.generic(404);

Since a web app module is not responsible for starting the web server itself, it no longer needs a port number config setting or even a dependency on http. Other config settings should be provided by the host app on initialization, as shown above. This keeps all config settings in the host app, and encourages sensible defaults when writing your web app module. Be sure to read the post on tips for app configuration, which apply equally to config options for initializing a module.

Virtual hosting is a simple concept, and it lends itself well to the Simpl.js app/module structure. Using Simpl.js to implement virtual hosting also saves you the trouble of learning the custom config languages that come with standard web servers like Apache and NGINX.