How to deploy Next.js app in production server

How to deploy Next.js app in production server

Introduction

Next.js is a popular open-source framework for building server-side rendered React applications. When it comes to deploying a Next.js app in production, there are several steps that you need to follow to ensure a smooth and error-free deployment.

In this blog post, we'll walk through the steps for deploying a Next.js app in production. We'll cover how to configure your app for production, how to build your app for deployment, and how to deploy your app to a server or hosting platform.

Step 1: Configure your app for production

Before you can deploy your Next.js app in production, you need to make sure that it's properly configured for production use. Here are a few things to keep in mind:

Use environment variables

When deploying a Next.js app in production, it's important to use environment variables to manage sensitive data such as API keys, database credentials, and other secrets. You can use the dotenv package to load environment variables from a .env file into your app.

To do this, create a .env file in the root directory of your project and add your environment variables like this:

API_KEY=YOUR_API_KEY
DB_USER=YOUR_DB_USER
DB_PASSWORD=YOUR_DB_PASSWORD

Then, in your code, you can access these environment variables like this:

const apiKey = process.env.API_KEY;
const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASSWORD;

Set up your production database

If your app uses a database, make sure to configure it for production use. This might include creating a new database user with restricted permissions, enabling SSL encryption, and setting up a backup plan.

Use a production-ready server

Next.js includes a built-in development server that's great for local development, but it's not recommended for production use. Instead, you should use a production-ready server such as Express or Koa to serve your app.

To do this, create a custom server.js file in the root directory of your project, and use it to start your server. Here's an example using Express:

const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Step 2: Build your app for deployment

Once you've configured your Next.js app for production, you need to build it for deployment. This process generates a set of static HTML files that can be served by your production server.

To build your app, run the following command in your terminal:

npm run build

This will generate a /.next directory in your project's root directory, containing your app's build files.

Step 3: Deploy your app using PM2

Now that your app is built and ready for deployment, you need to choose a hosting platform or server to deploy it to. There are many options available, including:

In this tutorial, we'll use a Linux server running Ubuntu and deploy our app using PM2, a popular process manager for Node.js applications.

Step 1: Set up your server

First, you need to set up a Linux server with Node.js installed. Here are the steps to set up a new Ubuntu server:

  1. Create a new Ubuntu server on your hosting platform of choice. You can follow their instructions for creating a new instance.

  2. SSH into your server using a tool like PuTTY or the Terminal app on Mac or Linux.

  3. Update your server's package manager and install Node.js:

     sudo apt update
     sudo apt install nodejs npm
    

    This will install the latest version of Node.js and npm.

Step 2: Install PM2

Next, you need to install PM2 on your server. You can do this by running the following command:

sudo npm install pm2 -g

This will install PM2 globally on your server.

Step 3: Transfer your app files to the server

Now, you need to transfer your Next.js app files to the server. You can do this using a tool like SCP or SFTP, or by using Git to clone your app repository onto the server.

Once your app files are on the server, navigate to the app directory and install any dependencies:

cd /path/to/your/app
npm install
npm run build

Step 4: Start your app with PM2

To start your app with PM2, run the following command:

pm2 start npm --name "your-app-name" -- run start

Replace "your-app-name" with a name of your choice. This will start your app with PM2 and automatically restart it if it crashes or encounters an error.

Step 5: Set up PM2 to start on boot

To ensure that PM2 starts your app automatically when the server reboots, run the following command:

pm2 startup

This will generate a command that you need to run as sudo. Copy the command and run it:

sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u ubuntu --hp /home/ubuntu

This will set up PM2 to start on boot and automatically start your app.

Step 6: Monitor your app with PM2

You can use PM2 to monitor your app's logs and performance. To view your app's logs, run the following command:

pm2 logs your-app-name

Replace "your-app-name" with the name you chose in Step 4. This will display your app's logs in real time.

To view your app's performance metrics, run the following command:

pm2 monit

This will display a real-time dashboard of your app's CPU and memory usage, as well as other performance metrics.

NginX Conf

Generally the NginX conf is located in /etc/nginx/sites-enabled/ or /etc/nginx/sites-available

Create a new conf there with your domain name.

Replace example.com with your domain name.

Note: if your NextJS application is running on different port other then 3000, make sure to update that also.

server {
   listen 80;
   listen [::]:80;
   server_name example.com;


   location / {
        proxy_pass http://127.0.0.1:3000;

        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_set_header        Upgrade $http_upgrade;
        proxy_set_header        Connection "upgrade";
        proxy_redirect          off;
        proxy_http_version      1.1;
   }
}

Note: if you need the full server setup guide, you can follow this article:

Step by step server setup guide

Conclusion

In this tutorial, we've covered the steps required to deploy a Next.js app to production using PM2 as the process manager. We started by building the app for production and optimizing it for performance. Then, we set up a Linux server and installed PM2 to manage the app's process. After transferring the app files to the server, we started the app with PM2 and set it up to start on boot. Finally, we learned how to use PM2 to monitor the app's logs and performance.

With this knowledge, you should be able to deploy your own Next.js app to production using PM2 and monitor it for performance and reliability. Keep in mind that there are many hosting options and tools available, and you may need to adjust the steps depending on your specific setup. However, with a little practice and experimentation, you'll be able to deploy and manage your Next.js app with confidence.