How to Deploy your NextJS App on a VPS
Tags: nextjs, webdev, vps, ssl
Published: 2024-07-06 16:11:07

# Deploying Your Next.js Application on a VPS

Deployment — A crucial part of development that most crash courses and tutorials leave out of their curriculum. It is one of the underrated skills and a must-have to become an all-round developer. Today we are going to see how to deploy a Next.js application on a VPS (Virtual Private Server).

You must be thinking, why not just deploy it on Vercel? It is so simple and seamless. But let me tell you, while Vercel is a well-liked option, you might prefer to test on your own VPS or you might not feel comfortable with a managed hosting company, and the costs on Vercel increase exponentially very quickly.

This article will be a total guide on how to deploy your Next.js application, set up Nginx as a proxy server, connect your domain to the Next.js app, get an SSL certificate using Certbot, and run it using PM2. So let’s get started.

## Things to Have Beforehand

- Your own VPS
- A Next.js application
- Basic knowledge of SSH, Node.js, and basic Linux command-line usage
- Domain for your application (optional, you can check your app running directly on IP also)

## Set Up Your VPS

1. **Connect to VPS using SSH**: Replace `your-vps-ip` with the IP address of your VPS.

```
ssh root@your-vps-ip
```

2. **Install Necessary Software**

**Update and Upgrade**: Update the package list and upgrade installed packages to the latest versions.

```
sudo apt update
sudo apt upgrade -y
```

**Install Node.js and npm**: Install Node.js and npm on your VPS.

```
sudo apt install -y nodejs
```

**Install PM2**: PM2 is a process manager for Node.js applications. It keeps your app running and restarts it if it crashes.

```
sudo npm install -g pm2
```

## Deploy Your Next.js Application

Here are three ways to deploy your application:

1. **Transfer your application files to the VPS using SCP**: Use the command below from your local machine’s terminal. Replace the paths as needed.
    ```bash
    scp -r /path/to/your/nextjs-app root@your-vps-ip:/path/to/destination
    ```

2. **Clone your application from a GitHub repository**: If it is a public repo, clone directly (not recommended). For a private repo, generate SSH keys in your VPS and then copy the public key and put it in the keys section of your GitHub account to allow the VPS to clone your private repo using SSH.
    ```bash
    git clone <Your repository link>
    ```

3. **Create a new Next.js app on the VPS**:
    ```bash
    cd /path/to/your/nextjs-app
    npx create-next-app@latest myapp
    ```

Now that we have deployed our application, it’s time to set up a reverse proxy Nginx server and connect the domain to our application. Then at last, we will build our app and start it with PM2.

## Set Up a Reverse Proxy with Nginx

1. **Install Nginx**: Install Nginx, a web server that can act as a reverse proxy.
    ```bash
    sudo apt install nginx -y
    ```

2. **Adjust our Firewall**: To allow Nginx and traffic on ports 80 and 443.
    ```bash
    sudo ufw allow 'Nginx HTTP'
    sudo ufw allow 'Nginx HTTPS'
    sudo ufw enable
    sudo ufw status
    ```
    The status should show something like below:
    ```
    Status: active

    To                         Action      From
    --                         ------      ----
    OpenSSH                    ALLOW       Anywhere
    Nginx HTTP                 ALLOW       Anywhere
    OpenSSH (v6)               ALLOW       Anywhere (v6)
    Nginx HTTP (v6)            ALLOW       Anywhere (v6)
    ```

3. **Check if Nginx has started**:
    ```bash
    systemctl status nginx
    ```
    Verify by going to the IP of your VPS `http://your_vps_ip_address` on a browser; it should show the default Nginx page.

4. **Create Nginx Config**: Create an Nginx configuration file to forward web traffic to your Next.js application.
    ```bash
    sudo nano /etc/nginx/sites-available/nextjs-app.conf
    ```
    Paste the below configuration and replace `your-domain.com` with your domain.
    ```nginx
    server {
      listen 80;
      server_name your-domain.com;

      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;
      }
    }
    ```
    Now delete the default config file:
    ```bash
    sudo rm /etc/nginx/sites-enabled/default
    ```
    Enable our configuration by creating a symbolic link and restarting Nginx:
    ```bash
    sudo ln -s /etc/nginx/sites-available/nextjs-app.conf /etc/nginx/sites-enabled/
    sudo systemctl restart nginx
    ```

## Secure Your Application with SSL

 **Install Certbot with Snapd**:

*Install Snapd*:

```
sudo apt install snapd
```

*Ensure you have the latest Snapd version installed*:

```
sudo snap install core; sudo snap refresh core
```

*Install Certbot with Snapd*:

```
sudo snap install --classic certbot
```

*Create a symlink to ensure Certbot runs*:

```
sudo ln -s /snap/bin/certbot /usr/bin/certbot
```

**Obtain SSL Certificate with Certbot**:


```
sudo certbot --nginx -d your_domain_name.com -d www.your_domain_name.com
```


## Build Your Application and Start with PM2

Now that we have our app on the VPS, the domain connected with it, and SSL to secure it, it's finally time to build our Next.js app and get it running.

1. **Go to your app and run the build command**:
    ```bash
    cd /path/to/your/nextjs-app
    npm run build
    ```

2. **Start the application using PM2**:
    ```bash
    sudo pm2 start npm --name "myapp" -- start
    ```

3. **Save the PM2 process and set up PM2 to start on boot**:
    ```bash
    sudo pm2 save
    sudo pm2 startup
    ```

4. **Now go to your domain, and you will see your Next.js app running**:
    ```
    https://your-domain.com
    ```

## Conclusion

Deploying your Next.js application on a VPS might seem challenging at first, but by following these steps, you can set up your server, install the necessary software, transfer your application, and secure it with HTTPS. This process gives you more control over your application and can lead to better performance and cost savings. Happy deploying!

## Reference

- [Deploy NextJS App on VPS](https://medium.com/@zay_kyoy/deploy-nextjs-app-on-vps-20aedfbed3d1)

##Epilogue

Thank you for reading! If you have any feedback or notice any mistakes, please feel free to leave a comment below. I’m always looking to improve my writing and value any suggestions you may have. If you’re interested in working together or have any further questions, please don’t hesitate to reach out to me at [fa1319673@gmail.com](mailto:fa1319673@gmail.com).