Logo

How to Deploy a Next.js Project on a VPS

Introduction

Deploying a Next.js application on a Virtual Private Server (VPS) gives you complete control over your hosting environment, configuration options, and can be more cost-effective than managed hosting services for production applications. This guide will walk you through the entire process of deploying your Next.js project on a VPS, from initial server setup to continuous deployment strategies.

Prerequisites

Before you begin the deployment process, ensure you have the following:

  • A Next.js project ready for deployment
  • A VPS from providers like DigitalOcean, Linode, AWS EC2, etc.
  • A registered domain name (optional but recommended)
  • Basic knowledge of Linux commands
  • SSH access to your server

Setting Up Your VPS

After acquiring your VPS, the first step is to properly set it up for hosting your Next.js application. This includes securing your server and installing necessary software.

Initial Server Setup

Connect to your server via SSH and perform these essential setup tasks:

  • Update your system packages: sudo apt update && sudo apt upgrade -y
  • Create a new non-root user with sudo privileges
  • Set up SSH key authentication and disable password authentication
  • Configure a basic firewall with UFW

Installing Required Software

Install the necessary software for running your Next.js application:

  • Node.js and npm: sudo apt install nodejs npm
  • Install a more recent version of Node.js using NVM if needed
  • Git: sudo apt install git
  • Nginx: sudo apt install nginx
  • PM2 process manager: sudo npm install -g pm2

Preparing Your Next.js Project

Optimizing for Production

Before deploying your Next.js application, make sure it's optimized for production:

  • Update your next.config.js with appropriate production settings
  • Set up environment variables for production
  • Run a production build locally to check for any issues

Choosing a Deployment Strategy

Next.js offers multiple deployment options. For VPS deployment, consider:

  • Node.js Server: Running Next.js as a Node.js server
  • Static Export: Using next export if your app doesn't require server-side features

Deployment Process

Transferring Your Code

There are several ways to get your code onto the VPS:

  • Clone directly from your Git repository: git clone https://github.com/yourusername/your-nextjs-project.git
  • Set up a deployment workflow with GitHub Actions or similar CI/CD tools
  • Use SCP or SFTP to transfer files manually (not recommended for regular deployments)

Building Your Next.js Application

Once your code is on the server, build your Next.js application:

  1. Navigate to your project directory: cd your-nextjs-project
  2. Install dependencies: npm install
  3. Build the application: npm run build

Running with PM2

Use PM2 to manage your Node.js process:

  1. Start your application: pm2 start npm --name "next-app" -- start
  2. Ensure PM2 restarts on server reboot: pm2 startup
  3. Save the PM2 process list: pm2 save

Setting Up Nginx

Nginx will act as a reverse proxy for your Next.js application:

  1. Create a new Nginx configuration file: sudo nano /etc/nginx/sites-available/your-domain.com
  2. Add a basic configuration:
    server {
        listen 80;
        server_name your-domain.com www.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;
        }
    }
  3. Enable the site: sudo ln -s /etc/nginx/sites-available/your-domain.com /etc/nginx/sites-enabled/
  4. Test the configuration: sudo nginx -t
  5. Restart Nginx: sudo systemctl restart nginx

Configuring SSL with Let's Encrypt

Secure your site with a free SSL certificate from Let's Encrypt:

  1. Install Certbot: sudo apt install certbot python3-certbot-nginx
  2. Obtain and configure SSL certificate: sudo certbot --nginx -d your-domain.com -d www.your-domain.com
  3. Follow the prompts to complete the setup
  4. Certbot will automatically update your Nginx configuration
  5. Test automatic renewal: sudo certbot renew --dry-run

Continuous Deployment

Set up a continuous deployment workflow to automate future updates:

  • Create a deployment script on your server
  • Set up GitHub Actions or similar CI/CD service to trigger deployments on push
  • Configure webhooks to notify your server of new changes

A basic deployment script might look like:

#!/bin/bash
cd /path/to/your-nextjs-project
git pull
npm install
npm run build
pm2 restart next-app

Performance Optimization

Optimize your deployed Next.js application:

  • Configure Nginx caching for static assets
  • Enable Gzip compression in Nginx
  • Implement proper cache headers
  • Consider using a CDN for static assets
  • Monitor server resources and scale as needed

Troubleshooting

Common issues and their solutions:

  • 502 Bad Gateway: Check if your Next.js application is running and PM2 status
  • 404 Not Found: Verify Nginx configuration and routing
  • SSL Certificate Issues: Check Certbot logs and certificate renewal status
  • Performance Problems: Monitor server resources, check application logs

Useful commands for troubleshooting:

  • Check PM2 status: pm2 status
  • View application logs: pm2 logs next-app
  • Check Nginx error logs: sudo tail -f /var/log/nginx/error.log
  • Test Nginx configuration: sudo nginx -t