Skip to content

Node.js on Shared Hosting (Part 2)

Published on: February 7, 2021


Node.js on Shared Hosting (Part 2)

Okay so we have now successfully installed Node on our system.
Now we proceed to running an Express.js App on our shared server.

First, Let’s create a directory for the project. Remember this directory is outside your public_html.

Paste the below code to create a directory:

shell
mkdir node_app

Now open up your favourite IDE (I prefer IntelliJ) & create a simple Express.js App, take a look here for a hello-world app: https://expressjs.com/en/starter/hello-world.html

After you have created a basic project, simply upload it to your node_app directory that you created previously.

Now, let’s install the dependencies.
To do that just open your terminal again (ssh) and run -

shell
npm install

Here’s how it’d look:

npm install

So the dependencies are now installed & you can run Node, but you cannot access a directory outside public_html.

Your app will run successfully at http://localhost:3000 but you won’t be able to see it in action, so here’s how we solve that.

In your public_html directory, create a subdirectory via your cPanel/hPanel. Let’s name it the same as node_app. Your directory should be at: public_html/node_app. Create a .htaccess file & paste the below redirect config -

apache
RewriteEngine On
RewriteRule ^$ http://127.0.0.1:3000/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:3000/$1 [P,L]

# Note: Replace 3000 with the Port that you created in the Express Hello World App

What does this do? This tells the server (Apache) to simply redirect any requests to this directory i.e. https://you_domain.com/node_app to http://localhost:3000 which is hosting your Express App.

Now lets fire it up! Open your ssh terminal & move to the node_app directory (cd node_app) Type the command: node app.js & hit enter & you should see "Example app listening at localhost:3000".

Now go to url: https://your_domain.com/node_app & you should see a "Hello World", checkout below screenshot -

express hello world
🔥🤩🎉 You are running a Node Express App!🔥🤩🎉

The only limitation to this is that you cannot keep this app running indefinitely 😕! Because as soon as you close your SSH Connection, the Express App would stop running & the domain would return a 503 Service Unavailable.

To keep this running, you’d obviously need a VPS.

Darshan Pandya