Journal



running multiple Node.js apps on shared hosting with A Small Orange

Here’s a tutorial from A Small Orange for serving your website with Node.js.

Running multiple apps off one site is pretty simple - we just do the same process in a subdomain. What this looks like:

This is what mine looks like. I created src to hold all my project directories:

~
|-- src
|   |-- cool-app
|   |   |-- server.js
|   |   |-- index.html
|   |   |-- @app.js            # symlink to server.js
|   |   |-- package.json
|   |   |-- tmp
|   |   |-- public
|   |   |   |-- .htaccess

The .htaccess file should look like this:

PassengerEnabled on
PassengerAppRoot /home/user/src/cool-app
SetEnv NODE_ENV production
SetEnv NODE_PATH /usr/lib/node_modules

From A Small Orange help page:

Explaining the .htaccess Directives

Earlier we created an .htaccess file with four lines, or in this case directives. The server supports node.js through Phusion Passenger and that file is required to tell the web server to use Passenger, along with how it should be configured. Here are the directives, and how they are used:

PassengerEnabled on - tells the web server to enable Passenger
PassengerAppRoot /home/user/myapp - tells Passenger that our application is in /home/user/myapp
SetEnv NODE_ENV production - sets the environment variable NODE_ENV to production, which if your application uses it will relay to the application that it needs to use it’s production configuration
SetEnv NODE_PATH /usr/lib/node_modules - tells Passenger to also look for node.js modules in the global directory, where modules that the server provides exist.

The last step is to login to CPanel and create a subdomain pointing to the public folder, e.g.:

Subdomain:
coolapp

Domain:
janedoe.com

Document root:
/home/user/src/cool-app/public

Now requests to coolapp.janedoe.com will be handled by your server.js.

What’s going on:

Basically, we use the .htaccess file to re-configure how requests are handled. We can run any number of apps by creating subdomains and pointing them to any folder with an appropriately defined .htaccess.

I use this directory structure to keep things organised - each project I want to publish can have its own folder instead of residing in public_html, which is the default web root. Since I sync public_html directly with a local Jekyll project, it’s a pain to include anything manually.