Droplet/VPS Configuration with Nginx with Https For Node and NextJs
Tags: nginx, mern, javascript, vps
Published: 2024-04-18 03:57:03

In the ever-evolving landscape of web development, efficient server configuration is paramount to ensuring optimal performance and scalability of applications. With the emergence of versatile technologies like MERN (MongoDB, Express.js, React.js, Node.js) stack for JavaScript-based applications and PHP for server-side scripting, developers are empowered to create dynamic and interactive web experiences. However, the efficacy of these applications greatly relies on the underlying server infrastructure.

Enter Nginx, a high-performance web server renowned for its speed, scalability, and flexibility. Leveraging Nginx as the cornerstone of your Droplet/VPS (Virtual Private Server) configuration lays the foundation for a resilient and efficient hosting environment. This guide aims to walk you through the process of configuring Nginx to seamlessly accommodate both MERN and PHP applications on your Droplet/VPS.

**Why Nginx?**

Nginx's asynchronous, event-driven architecture makes it adept at handling concurrent connections with minimal resource consumption, making it an ideal choice for serving both static and dynamic content. Its robust feature set, including reverse proxying, load balancing, and SSL/TLS termination, empowers developers to optimize performance and security effortlessly.

**Step 1: Get SSH Username, Password and Connect to server using terminal**
If you are using vps from digital ocean then you need to first create a droplet according to your configuration and then click on your droplet and then you will find named console. After clicking on there you will find a terminal that directly connect to your server

![Droplet Screenshoot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjw6phav1s7c5pk3ba6g.png)

If your using external one then open your terminal and hit 

```
ssh username@serverip
```

then it take your password and give your password and login to your server.


**Step 2 – Installing Nginx**

```
sudo apt update
sudo apt install nginx
```

run above command to install nginx

**Step 3 – Adjusting the Firewall**

Before testing Nginx, the firewall software needs to be adjusted to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.

```
sudo ufw app list
```

As demonstrated by the output, there are three profiles available for Nginx:

![Nginx Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rzwini2kxi3vsy6a5x5.png)


Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)
Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)

It is recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Right now, we will only need to allow traffic on port 80.

You can enable this by typing:

```
sudo ufw allow 'Nginx HTTP'
```
You can verify the change by typing:
```
sudo ufw status
```
**Step 4 – Checking your Web Server**

We can check with the systemd init system to make sure the service is running by typing:

```
systemctl status nginx
```
Output:

![Nginx output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzom6yx44c0i66cpke9a.png)

now hit your ip to your browser you will find nginx landing page

**Step 5 — Installing Certbot**

The first step to using Let’s Encrypt to obtain an SSL certificate is to install the Certbot software on your server.

Install Certbot and it’s Nginx plugin with apt:

```
sudo apt install certbot python3-certbot-nginx
```

```
Step 6 — Confirming Nginx’s Configuration
```
Certbot needs to be able to find the correct server block in your Nginx configuration for it to be able to automatically configure SSL. Specifically, it does this by looking for a server_name directive that matches the domain you request a certificate for.

To check, open the configuration file for your domain using nano or your favorite text editor:

```
sudo nano /etc/nginx/sites-available/example.com
```

Find the existing server_name line. It should look like this:

...
server_name example.com www.example.com;
...

If it does, exit your editor and move on to the next step.

If it doesn’t, update it to match. Then save the file, quit your editor, and verify the syntax of your configuration edits:

```
sudo nginx -t
```

If you get an error, reopen the server block file and check for any typos or missing characters. Once your configuration file’s syntax is correct, reload Nginx to load the new configuration:

```
sudo systemctl reload nginx
```
**Step 7 — Allowing HTTPS Through the Firewall**

If you have the ufw firewall enabled, as recommended by the prerequisite guides, you’ll need to adjust the settings to allow for HTTPS traffic. Luckily, Nginx registers a few profiles with ufw upon installation.

```
sudo ufw status
```
To additionally let in HTTPS traffic, allow the Nginx Full profile and delete the redundant Nginx HTTP profile allowance:

```
sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'
```

**Step 8 — Obtaining an SSL Certificate**
Certbot provides a variety of ways to obtain SSL certificates through plugins. The Nginx plugin will take care of reconfiguring Nginx and reloading the config whenever necessary. To use this plugin, type the following:

```
sudo certbot --nginx -d example.com -d www.example.com
```
This runs certbot with the --nginx plugin, using -d to specify the domain names we’d like the certificate to be valid for.

If this is your first time running certbot, you will be prompted to enter an email address and agree to the terms of service. After doing so, certbot will communicate with the Let’s Encrypt server, then run a challenge to verify that you control the domain you’re requesting a certificate for.

**Step 8: Setting Up for MERN**
Update and upgrade the packages on the droplet:

```
sudo apt update && sudo apt upgrade -y
```
Nginx is the tool that will handle all the routing to our Next.js application. Create a new Nginx configuration file for your Next.js application:

```
sudo nano /etc/nginx/sites-available/nextjs
```

Paste the following configuration, replacing server_name with your domain name or droplet IP address:

```
server {
  listen 80;
  server_name YOUR_IP_ADDRESS;
  location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}
```
Save and close the file. Create a symbolic link to enable the configuration:

```
sudo ln -s /etc/nginx/sites-available/nextjs /etc/nginx/sites-enabled/
```
Test the Nginx configuration for any syntax errors:

```
sudo nginx -t
```
Now clone your git repo in your server. Then run

```
npm install
```
Build the Next.js application:

```
npm run build
```
Finally, start the Next.js application:

```
npm start
```
Your Next.js application is now deployed and accessible at your domain name or droplet IP address. To keep your application running in the background and automatically restart on crashes or server reboots, you should use a process manager like PM2

**Step 9: Setting Up PM2 Process Manager**

We ran npm start from within our Droplet. Sometimes this command may stop running for reasons like the server restarted or it needed to install updates. We will use a tool called PM2 to make sure that our Next.js application is always running. PM2 will even restart the Next.js application if it goes down.

To install PM2 globally on your droplet:

```
sudo npm install -g pm2
```
Start the Next.js application using PM2:

```
pm2 start npm --name "nextjs" -- start
```
This command will generate a script that you can copy and paste into your terminal to enable PM2 to start on boot.

Save the current PM2 processes:

```
pm2 save
```
For NodeJS Run via PM2

```
pm2 start app.js --name "my-express-app"
```
**Conclusion**
In this section, I tried to complete all part related to VPS configuration for node and Next JS. Hopefully its find you good. If facing any problem, Comment section is open