Running a Node.js application on your cPanel website

Node.js is a platform built on Chromes JavaScript runtime for easily building network applications that are quick and scalable. A history Node.js can be found below:

What is Node.js?

Before diving into Node.js it is important to understand the difference between server-side scripting and client-side scripting.

Server Side Scripting: The use of programming (using languages such as PHP, ColdFusion, ASP, .NET, etc.) to process data and produce dynamic web page content. This makes for a personalized user experience, such as e-commerce websites marketing towards a specific user based on their preferences and history.

Client Side Scripting: The use of JavaScript that executes code both during and after a web page is loaded. This is performed on the client’s browser (such as Chrome, FireFox, etc.) to manipulate items displayed on a web page.

Typically web developers have to learn both server-side scripting in addition to JavaScript to make a good user experience on websites they develop.

Now let’s get back into explaining what Node.js is and how it works.

Node.js is a very popular server environment that combines Googles V8 JavaScript engine, an event loop, and a low-level I/O API. Their official documentation states the following:

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Node.js

With the use of Node.js developers can now perform all development using a common language: JavaScript

This means you can create web applications without the need for additional languages, such as PHP. Many other languages such as PHP block functions from running until the previous function finishes. With Node.js functions are non-blocking which means that commands can execute concurrently and use callbacks to signal completion or failure of a function.

Node.js is a very popular option for developers due to its easy creation of web applications, huge list of pre-built modules and classes, as well as how lightweight it is compared to other platforms.

Installing Node.js on cPanel server

The later versions of WHM & cPanel support installation of Node.js and the install are very quick and simple. Follow the steps below to install Node.js on your server:

Install via WHM Interface:

  1. Login to your servers WHM interface.

  2. In the top-left of the page is a search box. Enter ‘EasyApache’ and choose the option for EasyApache 4.

    Note: If your server shows you don’t have EasyApache 4 installed and are instead on EasyApache 3 please contact our support for assistance instead of attempting the upgrade, as a great number of upgrades result in failure and possible corruption of Apache requiring a restore to restore functionality.

  3. In EasyApache 4 click on the button labeled ‘Customize’.

  4. You should see a list of options that you can use to install/uninstall different features and components. Click on the option for ‘Additional Packages’.

  5. Check the toggle button next to nodejs10, then click the button for Next. It will ask you to review the list of changes… do so and click the button for Provision to finish the installation.

Install via command line:

  1. Open command line (SSH/Terminal) for your server. If needed you can utilize the ‘Terminal’ feature within your WHM interface or you can just follow the steps above for the interface install steps instead.

  2. Run the following command:

    yum install ea-nodejs10 -y
    
  3. Wait for the setup to finish, which should only take a few seconds. You should get a message in terminal stating the process completed.

It is recommended to create a symlink for NPM that allows you to perform module installations easily via the command ‘npm’ without having to provide the full path to the EasyApache Node scripts.

  1. Open command line (SSH/Terminal) for your server. If needed you can utilize the ‘Terminal’ feature within your WHM interface or you can just follow the steps above for the interface install steps instead.

  2. Run the below commands:

    ln -s /opt/cpanel/ea-nodejs10/bin/npm /usr/local/sbin/npm
    ln -s /opt/cpanel/ea-nodejs10/bin/node /usr/local/sbin/node
    

    Then:

    chmod +x /usr/local/sbin/npm
    chmod +x /usr/local/sbin/node
    

    The first scripts will first set the symbolic links and the second scripts will set executable permissions for the scripts to be able to perform. You should be complete!

Setting up your node application

The steps below will show how to create a new node application (that is listening on a specific port of your choosing) on the server. You’ll want to make sure to have the port open on the servers CSF firewall as well as your servers IP outside of our normal firewall (otherwise port might be blocked by our network).

  1. Open command line (SSH/Terminal) for your server. If needed you can utilize the ‘Terminal’ feature within your WHM interface or you can just follow the steps above for the interface install steps instead.

  2. Change the directory (cd command) of your command line/terminal session to the root of your application.

    cd /home/{user}/public_html/
    

    For example if your cPanel username is ‘serverma’, then the folder path could be: /home/serverma/public_html/

  3. If you already have a node application built, then upload the files here at this time (You can use an FTP application such as FileZilla to move your files to the /public_html/ folder).

    If you do not have a node application already installed, then run the command below:

    npm init -y
    

    The above command will initialize the node package and place the contents of your application config into a package.json file. This file contains important information about your node app. You can update the contents of this file using nano, such as the below code after the init command above finishes.

    nano package.json
    

    If you are creating your first node application and do not yet contain a .js file in the root of your application, then go ahead and create one now (such as app.js). You can create the file using nano with the same command as mentioned above… replacing ‘package.json’ with the name of the file you want to create. Once created you can update the package.json file to use that new filename as the ‘main’ file for the app.

    If you need example code to use, then please toggle the below section for an example script:

    Example script for node.js

    An example of a node.js script can be found below. Again, remember to update the port to the actual port you want to use. Some ports may already be in use on the server (such as ports 80 and 443 as these are in use by Apache).

    The port doesn’t really matter as long as it’s open as the visitors to the website won’t see it. Be sure to change the ‘domain.com’ to your actual website domain.

    const http = require('http')
    const hostname = 'domain.com';
    const port = 8080;
    
    const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello! NodeJS is awesome! \n');
    });
    
    server.listen(port, hostname, () => {
      console.log(`Node.js App Server at http://${hostname}:${port}/`);
    });
    
  1. Now that your application has been created or uploaded to the website let’s start the application so it’s listening within node on the server. To do so run the following command (replacing app with your main application file name. Example if the main file is main.js then change app to main):

    node app &
    

    It is important to include the & in the command otherwise, the application will quit after you exit out of the node window on your terminal session.

    If the server is ever rebooted then the app will no longer be started unless you add your app to the node service ExecStart list or install and configure PM2.

  2. You now want to set your website to use the node application. To do so create or edit the websites .htaccess file on the main root directory (/public_html/). Add the following code to the file:

    DirectoryIndex disabled
    RewriteEngine On
    RewriteRule ^$ http://domain.com:8080/ [P,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ http://domain.com:8080/$1 [P,L]
    

    Note: The hostname set in the node application needs to match the hostname used here in the rewrite rule.

    Your node application should be running and you should be able to access it via the website (as long as the CONST in the node app and rewrite rule is properly configured, as well as DNS is pointing to the server for the domain in question).

Installing node modules

There are tons of already made modules available for users to install within their application. Node Package Manager (NPM) makes this process extremely easy and can be seen below:

Note: If you haven’t already created symlinks for NPM you should do so now.

  1. Open command line (SSH/Terminal) for your server. If needed you can utilize the ‘Terminal’ feature within your WHM interface or you can just follow the steps above for the interface install steps instead.

  2. Change the directory (cd command) of your command line/terminal session to the root of your application.

    cd /home/{user}/public_html/
    

    For example if your cPanel username is ‘serverma’, then the folder path could be: /home/serverma/public_html/

  3. As long as you are in the directory your node application is installed in (normally installed in /public_html of website) then run the command below.

    npm install example-module
    

    The above example command would look for a module named ‘example-module’. You’ll need to obtain the actual name of the module you’re wanting to install (from the module creator) and then replace ‘example-module’ with the actual module you’re wanting. This should automatically install the module for your node application and all the necessary assets.