Setting up Nginx reverse Proxy for Next JS Application
Configuring Nginx as a Reverse Proxy for Next.js
Steps
Install node js (In case you are following along in OS other than Ubuntu follow https://github.com/nodesource/distributions)
Create a Next Js application
Build the Nextjs application
Start the Next JS project from
pm2
Install Nginx
Create a site for Nextjs in Nginx and disable the default site
Enable New Nginx Site for Next js
Test the Application at
domain.com
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
NODE_MAJOR=18
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
Create A Next JS Project
npx create-next-app nextapp
Build the Nextjs application
cd nextapp
npm run build
Start the Next JS Project
Before starting the project make sure to change the directory to next js Application
# Start the Next Application with pm2
# we will start our application with pm2
# install pm2
sudo npm i -g pm2
pm2 start npm --name 'app-with-nginx-proxy' -- run start
# Verify Application is running fine
pm2 status
Install Nginx
sudo apt install nginx -y
Create a Nginx Configuration for the Next JS Proxy
sudo vim /etc/nginx/sites-available/next-proxy.conf
Paste the below content to the configuration, Make sure to change the server name to your domain name
server {
listen 80;
listen [::]:80;
server_name site_name www.site_name;
location / {
proxy_pass http://localhost:3000;
}
}
Enable Nginx Site for Next js and Restart Nginx
sudo ln -s /etc/nginx/sites-available/next-proxy.conf /etc/nginx/sites-enabled/next-proxy.conf
# unlink the default site
sudo unlink /etc/nginx/sites-enabled/default
sudo systemctl restart nginx
Test
If you are testing this in your local lab environment, virtual box, or EC2 and you don't have a domain ., add an entry to the /etc/hosts
file on your main laptop(valid for Linux and Mac OS). Map the domain name (sitename.com) to the IP address of your Ubuntu server.
Launch your Browser and open sitename(or whatever you set in server_name in Nginx and also DNS is setup )
Proxy Header
If your backend application requires information about the original client IP address, you may need to configure Nginx to pass the correct headers to your proxy. For example:
location / {
proxy_pass https://127.0.0.1:3000/;
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;
}