DarShan Pandya

NodeJs on Shared Hosting (Part 2)

Okay so we have now successfully installed Node on our server.
Now we go to running an Express App.

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:

mkdir node_app

Now open up your favourite Node IDE (I prefer IntelliJ) & create a simple ExpressJs 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

npm install

Here’s how it’d look:

So the dependencies are now installed & you can run Node but….
Yes!, you cannot access a directory outside public_html.
Your Node App will run successfully at http://localhost:your_port
but you won’t be able to see it in action, so here’s how we solve that.

In you public_html directory, create a sub-directory via your cPanel/hPanel file-manager.
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:

# Redirecting to appropriate port

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?
It tells the server (Apache) to simply redirect any requests to this directory i.e https://you_domain.com/node_app to https://localhost:your_port which is hosting your Node / 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 http://localhost:your_port”.

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


🔥🤩🎉 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 Node / Express App would stop running &
the domain would return a 503 Service Unavailable.
To keep this running, you’d obviously need a VPS.

Leave a Comment