How to host your NodeJS app on a server

How to host your NodeJS app on a server cover image

Category: WebDev

Posted at: Jun 12, 2024

2 Minutes Read

There are few good options for hosting your Node.js application, but one of the best ways is to host it on a Linux server or your own VPS. In this blog, I will demonstrate how to host your API and install the necessary tools to ensure it runs 24/7.

Requirements

You will need to install Node.js, forever, and Caddy.


Node.js: to run your application

$ sudo apt install nodejs


forever: A simple CLI tool for ensuring that a given script runs continuously (i.e. forever).

$ sudo npm install forever -g


Caddy: Fully-Managed HTTPS Reverse Proxy, it will take care of your SSL certificate and updates it automatically

$ sudo apt install caddy

Run your application

First, use forever to run the application continuously

forever start app.js

Other useful commands:

forever restart app.js
forever stop app.js

See more commands for troubleshooting


Caddy configuration

Update the Caddy file with the following configuration:

$ sudo nano /etc/caddy/Caddyfile

YOUR-DOMAIN.com {
       # Set this path to your site's directory.
       root * /usr/share/caddy

       # Enable the static file server.
       file_server

       # Another common task is to set up a reverse proxy:
       reverse_proxy localhost:7000
}

In my case, the application was hosted on port 7000. Replace this with the port your application is using.


After that, restart the service using this command:

$ sudo systemctl restart caddy

Domain

Finally, don' forget to add a DNS record that points to your server:

Note: If you want to create a sub-domain, replace the '@' with a name like 'api'


If you need any assistance, feel free to email me at me@husainm.com


Good luck!