Before we begin, make sure that you have the following prerequisites:
- An Ubuntu server with a non-root user with sudo privileges
- Nginx installed on your server
- Node.js and npm installed on your server
- A Next.js application ready to be deployed
Create a Systemd service for your application
Create a Systemd service to manage the application. This service will be used to start and stop the application.Create a new file in the /etc/systemd/system directory with the following content:
sudo nano /etc/systemd/system/nextjs.service
[Unit] Description=Next.js [Service] ExecStart=/usr/bin/npm start WorkingDirectory=/var/www/your-next-js-app Restart=always User=www-data [Install] WantedBy=multi-user.target
/var/www/your-next-js-app with the path to your Next.js application.
Start the Next.js
Systemd service using the following command:
sudo systemctl start nextjs
Configure Nginx as a reverse proxy
Create a new Nginx server block to serve as a reverse proxy for your application.
Create a new file in the
/etc/nginx/sites-available directory with the following content:
/static/ block is used to serve static files from the /static directory in your Next.js application with a 1-day cache expiration and the Cache-Control header set to public,
max-age=31536000, immutable, indicating that the files can be cached by the browser and intermediate proxies for up to 1 year.
Activate gzip compression for the Nginx server and determine the file types to compress using the gzip_types directive.
As before, replace your domain name and
/path/to/cert.key with the path to your SSL certificate and key, respectively.Save the file, create a symbolic link to it in the
/etc/nginx/sites-enabled directory, test the Nginx configuration, and reload Nginx to apply the changes, just as before.
Now, your Next.js 13 application is served behind Nginx with HTTP/2, gzip compression, and static file caching.