Hosting Node.js App on Shared Hosting

UtkarshUtkarsh
2 min read

Overview

If you have ever tried hosting your Node.js App for free, you would notice that most of the hosting service providers provide only the shared hosting plan for free. Hosting your Node.js application on these shared hosting servers can be very tedious sometimes.

Most of the time, the Shared Hosting Servers are preinstalled with PHP and provide CPanel to interact with your hosting server.

In this article, we will discuss how we can host a Node.js application on a shared hosting plan.

Hosting your Node.js App on Shared Hosting

  1. **Login into SSH from your terminal. **

Use ssh -p port username@IpAddress to login.

When the terminal asks for the password, enter the password and press enter.

You may get the SSH credentials from the CPanel or may have to contact your hosting provider for SSH credentials.

  1. Install the NVM on your Server.

Now, you can use SSH to install anything on the server. To install NVM, run the following command -

wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash

Now, run nvm install stable

  1. Confirm that the NVM is installed

Now, that you have installed the NVM, close the terminal and login into SSH using Step 1. Now, run the following commands -

node -v

npm -v

  1. Create .htaccess file

Now, create a .htaccess file inside the public_html directory in your server using the following commands -

cd ~/public_html

nano .htaccess

Now, copy the below-given lines into the file and replace XXXXX with the port you want to use in your app -

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

Upload your Node.js application inside the public_html directory using CPanel.

  1. Running your app

Now run your app via the SSH logged-in terminal as you would normally run on your local computer using node app.js or node server.js. This will host your Node.js application on your domain.

However, you'll notice that when you close the terminal, the application stops working. To avoid that you can just use node app.js & or node server.js &.

The more favourable way to continue hosting your application even after closing the terminal would be using an npm package called forever. To use the package, you can execute the following commands -

npm install -g forever

forever start app.js

Now, your Node.js application has been hosted on a shared hosting server.

giphy.gif

1
Subscribe to my newsletter

Read articles from Utkarsh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Utkarsh
Utkarsh

I'm a MERN Stack developer and technical writer that loves to share his thoughts in words on latest trends and technologies. For queries and opportunities, I'm available at r.utkarsh.0010@gmail.com