How to Deploy React with Next.js on an Nginx Server

Tiempo de lectura: 2 minutos

To deploy the web application we have created with React and Next.js, we will follow these steps:

run npm build

Make sure to replace your-domain.com with your actual domain and /path/to/your/application/build with the actual path to your Next.js application’s build folder.

   sudo systemctl restart nginx

It is important to note that Nginx will only serve the static files generated by Next.js. If your Next.js application uses server-side functions (such as getServerSideProps or getInitialProps), you need to ensure that your Nginx configuration does not interfere with these functions and that your application is properly configured to handle these requests.

server {
    listen 80;
    server_name tu-domino.com;

    location / {
        root /ruta/a/tu/aplicacion/build;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

To make your Next.js application compatible with getServerSideProps or getInitialProps, you need to configure Nginx to proxy requests that require server-side processing to your Next.js application.

Make sure to replace your-domain.com with your actual domain and your-nextjs-app-port with the port on which your Next.js application is running (e.g., 3000 if you are using the Next.js development server).

This Nginx configuration proxies all requests to your Next.js application, allowing getServerSideProps or getInitialProps to execute properly on the server.

server {
    listen 80;
    server_name tu-dominio.com;

    location / {
        proxy_pass http://localhost:puerto-de-tu-aplicacion-nextjs;
        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;
    }
}

After updating the Nginx configuration, make sure to restart the Nginx service for the changes to take effect:

sudo systemctl restart nginx

getServerSideProps or getInitialProps to handle requests and render the page on the server as needed.

Leave a Comment