Deploy Node JS app on VPS or Dedicated server

In this article, we are going to teach you how you can deploy the Node JS app on a VPS (Virtual Private Server) or a dedicated server. Make sure you have Node JS, NPM (Node Package Manager), and PM2 (Process Manager) installed, you can run the following commands to see if they are installed.

node -v
npm -v
pm2

If any of them is not installed on your server, you can simply chat with your hosting provider’s customer support center or open a ticket and ask them to install these for you. The main thing you are going to need for deployment is pm2.

Creating a Node JS server

First, create a sub-domain for example “node.adnan-tech.com”. It will also create a directory for this sub-domain. Then create a simple Node JS app in it by running the following command in your cPanel terminal:

npm init

Press Enter key for all questions to set the default values. Then install the following modules:

npm install express http cors express-formidable socket.io

Inside the directory created for the sub-domain, create a file named “server.js” and write the following code in it:

server.js

const express = require("express")
const app = express()

const cors = require("cors")
app.use(cors())

const expressFormidable = require("express-formidable")
app.use(expressFormidable())

const http = require("http").createServer(app)
const socketIO = require("socket.io")(http, {
	cors: {
		origin: "*"
	}
})

const port = process.env.PORT || 3000

http.listen(port, function () {
	console.log("Server started at port: " + port)

	socketIO.on("connection", function (socket) {
		console.log("User connected: " + socket.id)

		// [listen events here]
	})
	
	app.get("/", function (request, result) {
	    result.send("Hello world !")
	})
	
	// [create API here]
})

Then you need to tell your Node JS app that you will be using server.js as the main file. So open your package.json file and set the main key’s value to “server.js” as follows:

package.json

"main": "server.js",

Deploy the Node JS app

Now to start the server, first, open your “Terminal” from cPanel, and go to your subdomain by running the command:

cd yoursubdomain.com

Or whatever your subdomain path is. Then run the following command to start the server:

pm2 start server.js --name "Name of your app" --watch

–name is used to set a specific name for your app.

–watch is used to automatically restart the server if there is any change in the server.js file.

List all processes using pm2

You can view the list of all processed from the command:

pm2 list

If the write the URL https://yoursubdomain:3000/ in the browser, you will see the text “Hello world”. It means your Node JS server is successfully deployed on your VPS or dedicated server.

Create an API in Node JS

Now write the following code to create an API in the [create API here] section:

app.post("/myAPI", function (request, result) {
    const name = request.fields.name
    
    result.json({
        status: "success",
        message: "API has been called.",
        data: "Your name is " + name
    })
})

Then create an index.html file anywhere in your domain and write the following code to it to call an AJAX to this Node JS server.

index.html

<script>
	const ajax = new XMLHttpRequest()
	ajax.open("POST", "https://yoursubdomain:3000/myAPI", true)

	ajax.onreadystatechange = function () {
		if (this.readyState == 4) {
			if (this.status == 200) {
				console.log(this.responseText)
			}
		}
	}

	const formData = new FormData()
	formData.append("name", "Adnan")
	ajax.send(formData)
</script>

Open your browser console tab and you will see the message “Adnan”. Try changing the value in the “name” field in the formData object and refresh the page, you will now see your updated value.

Socket IO

You can also connect sockets to this Node JS server. In your index.html file, first, include the socket IO JS library using CDN:

<script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>

Then write the following Javascript code to connect the client with the server:

<script>
	const socketIO = io("https://yoursubdomain:3000")
</script>

After that, emit a simple event to the server:

// index.html

socketIO.emit("newEvent", { name: "Adnan" })

Then in your server.js, write the following code in place of the [listen events here] section:

// server.js

socket.on("newEvent", function (data) {
	socket.emit("newEvent", data)
})

And finally, on your client side, you need to listen to this event and display a message in the browser console:

// index.html

socketIO.on("newEvent", function (data) {
	console.log(data)
})

Refresh your page now and open your browser console. You will now see an object in the console. It means that your Node JS server’s sockets are running fine.

Stop the pm2 process

By default, the pm2 process will keep on running forever. If you want to stop the process, you can simply enter the following command in your cPanel terminal:

pm2 stop "Name of your app"

Run pm2 list and you will now see the status of your process as stopped.

Remove the pm2 process

Similarly, you can remove the pm2 process by running the following command:

pm2 delete "Name of your app"

Run pm2 list and you will no longer see your process in the list.

So that’s how you can deploy a Node JS app on your VPS or dedicated server. Check our tutorial to deploy Node JS app on the Heroku server. If you face any problems in following this, kindly do let me know.