Host Next.js Application with Nginx on Ubuntu

By Anurag Singh

Updated on Sep 04, 2024

Host Next.js Application with Nginx on Ubuntu

In this tutorial, we'll explain how to host Next.js Application with Nginx on Ubuntu 24.04 server. 

Next.js is a powerful React framework that enables developers to build fast, user-friendly web applications and websites. It simplifies the process of creating both static and dynamic web pages, offering built-in features like server-side rendering (SSR) and static site generation (SSG). These features enhance performance and SEO by allowing pages to be pre-rendered on the server.

Next.js also supports API routes, enabling developers to build full-stack applications within a single framework. With automatic code splitting, optimized performance, and a rich ecosystem of plugins and tools, Next.js is widely used for creating robust, scalable applications that deliver excellent user experiences. It integrates seamlessly with popular tools and platforms, making it a versatile choice for modern web development.

Deploying a Next.js application on an Ubuntu VPS with Nginx as the reverse proxy is a reliable and efficient way to serve your web application. In this tutorial, we’ll walk through the steps to set up and deploy a Next.js application on an Ubuntu server using Nginx.

Prerequisites

Before you begin, make sure you have the following:

  • A server running Ubuntu 24.04 dedicated server or KVM VPS.
  • Basic knowledge of the Linux command line.
  • A root user access or normal user with sudo rights.

Host Next.js Application with Nginx on Ubuntu

Step 1: Update and Secure Your Server      

Before deploying your application, it’s essential to update your server packages and secure it.

sudo apt update && sudo apt upgrade -y

Step 2: Install Node.js and npm

For latest version, visit the Node.js official documentation page.

# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 20

Verify the installation:

# verifies the right Node.js version is in the environment
node -v # should print `v20.17.0`

# verifies the right npm version is in the environment
npm -v # should print `10.8.2`

Step 3: Deploy Next.js Application

There are two ways to deploy it. First clone your Git repository or create a Next.js application in the server. We have covered both ways.

Clone Git Repository

Next, you'll need to transfer your Next.js application to your VPS. If your project is hosted on GitHub, you can clone it directly:

git clone https://github.com/yourusername/my-nextjs-app.git

Navigate into your project directory:

cd my-nextjs-app

Install Dependencies and Build the Application. Inside your project directory, install the necessary dependencies:

npm install

Build your Next.js application:

npm run build

Create a Next.js Application

Let's proceed with the installation.

Run the following command to create a new Next.js application using the create-next-app tool:

npx create-next-app@latest my-nextjs-app

Above command will prompt questions:

create-next-app@14.2.7
Ok to proceed? (y) y

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes

Navigate to the Project Directory. After the project is created, navigate into the project directory:

cd my-nextjs-app

To build the application for production, use:

npm run build

Step 4: Install and Configure PM2

PM2 is a process manager for Node.js applications that ensures your application stays online.

npm install -g pm2

Start your Next.js application with PM2:

pm2 start npm --name "my-nextjs-app" -- start

To ensure PM2 starts your application on system boot, run:

pm2 startup systemd
pm2 save

Check the status 

pm2 status

Output:

┌────┬────────────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name               │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├────┼────────────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0  │ my-nextjs-app     │ default     │ 0.40.0  │ fork    │ 4189     │ 50s    │ 0    │ online    │ 0%       │ 55.1mb   │ root     │ disabled │
└────┴────────────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

Step 5: Configure Firewall

If you have enabled UFW firewall, you need to add ports HTTP and HTTPS:

ufw allow 80/tcp
ufw allow 443/tcp
ufw reload

Step 6: Install and Configure Nginx as a Reverse Proxy

Install Nginx:

sudo apt install nginx -y

Create a new Nginx configuration file for your application:

sudo nano /etc/nginx/sites-available/your-nextjs-app

Add the following configuration:

server {
    listen 80;
    server_name your_domain_or_ip;

    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;
    }
}

Replace your_domain_or_ip with your domain name or server IP address. Save and close the file.

Create a symbolic link to enable this configuration:

sudo ln -s /etc/nginx/sites-available/your-nextjs-app /etc/nginx/sites-enabled/

Test the Nginx configuration to ensure there are no errors:

sudo nginx -t

If the test is successful, restart Nginx:

sudo systemctl restart nginx

Step 7: Secure Your Application with SSL

It's highly recommended to secure your application with SSL. You can use Certbot to obtain a free SSL certificate from Let's Encrypt.

First, install Certbot:

sudo apt install certbot python3-certbot-nginx -y

Then, run Certbot to obtain and configure the SSL certificate:

sudo certbot --nginx -d your_domain

Certbot will automatically configure SSL for your Nginx site.

Step 8: Verify Your Deployment

Your Next.js application should now be running on your domain https://your_domain. Visit your domain in a web browser to verify that everything is working correctly.

Conclusion

You have successfully seen how to host Next.js Application with Nginx on Ubuntu 24.04 server. With Nginx handling incoming traffic and PM2 managing the application process, your Next.js app is well-equipped to handle production workloads. Remember to keep your server and application updated to ensure optimal security and performance.