Question

How to deploy NextJS with NGINX?

So I know how to deploy a React app on a server.

  • npm run build
  • create a server block and point the root to my react app folder build (root /var/www/xfolder/build;)
  • systemctl restart nginx
  • run my node server (nohup node server &&) and its done.

I feel kind of dumb for not understanding this with NextJS. I run npm run build enter image description here

I'm expecting something like a build folder. I've tried setting the server block root to /var/www/xfolder/.next but the page still gives 403 forbidden. And do I need to run npm run start? I'm confuse on how to properly deploy the app. I'm using Ubuntu, NginX (1gb droplet) in DigitalOcean.

 46  103615  46
1 Jan 1970

Solution

 22

Check this: https://gist.github.com/iam-hussain/2ecdb934a7362e979e3aa5a92b181153

Reference for HTTP/HTTPS: https://gist.github.com/iam-hussain/2ecdb934a7362e979e3aa5a92b181153

Start PM2 nextJS service on port 8080:

  • cd PROJECT_DIRECTORY
  • pm2 start "npm run start -- -p 8080" --name contractverifier

Configure Nginx:

Replace this file with the below code /etc/nginx/sites-available/default

    server {
        server_name www.DOMAINNAME.com DOMAINNAME.com;

        index index.html index.htm;
        root /home/ubuntu/PROJECT_FOLDER; #Make sure your using the full path

        # Serve any static assets with NGINX
        location /_next/static {
            alias /home/ubuntu/PROJECT_FOLDER/.next/static;
            add_header Cache-Control "public, max-age=3600, immutable";
        }

        location / {
            try_files $uri.html $uri/index.html # only serve html files from this dir
            @public
            @nextjs;
            add_header Cache-Control "public, max-age=3600";
        }

        location @public {
            add_header Cache-Control "public, max-age=3600";
        }

        location @nextjs {
            # reverse proxy for next server
            proxy_pass http://localhost:8080; #Don't forget to update your port number
            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;
        }

        listen 80 default_server;
        listen [::]:80;
}
2021-11-02

Solution

 15

I managed to make it work. The problem is on my Nginx server block. I just add this block

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

then run

npm start

enter image description here

2020-10-16