Deploying a Next.js 14 Static Export with Nginx

Ismail Demirbilek
2 min readJun 8, 2024

--

Next.js supports static export (server-side generation), which allows for a fully static app rendered during build time. This feature is particularly useful for deploying highly performant and secure applications. However, deploying it on-premise with Nginx can be cumbersome. This guide provides quick and essential information to get your site up and running in no time.

Photo by Nubelson Fernandes on Unsplash

To get started, refer to the official Next.js documentation on static exports for enabling static exporting. This guide focuses on deployment specifics, assuming you already have a static site built and ready for deployment with Nginx.

Of course, we will build a container image based on Nginx.

Creating the Dockerfile

Our deployment process involves building a container image based on Nginx. Below is an example Dockerfile with a 3-step build process:

  1. Install Dependencies
# dependencies image
FROM node:20 as base
WORKDIR /app
COPY package*.json ./
# install dependencies
RUN npm ci

If you use a package manager other than npm, update the COPY command accordingly.

2. Build Static Files

# builder image
FROM base as builder
WORKDIR /app
COPY . .
RUN npm run build

3. Prepare Nginx

# production image
FROM nginx:stable as production
WORKDIR /app
COPY --from=builder /app/out /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

Complete Dockerfile

Dockerfile

Configuring Nginx

Here’s an example Nginx configuration file nginx.conf:

nginx.conf

Please note that redirects specified in next.config.js do not take effect in static exports. You must write redirect rules in the Nginx configuration file.

Handling Redirects in next.config.js

next.config.js

If your application requires redirects like above, you should write the following rewrite rule in your Nginx configuration (you can add as many rewrite rules as you need):

nginx.conf

Testing and Troubleshooting

After building and deploying your Docker image, test your setup to ensure everything is working as expected. Here are a few tips:

  • Check Nginx logs: Look at the Nginx error and access logs for any issues.
  • Verify file paths: Ensure that the static files are correctly located in /usr/share/nginx/html.
  • Validate redirects: Test all redirects to confirm they are working properly.

By following this guide, you should be well-equipped to deploy your Next.js static site with Nginx efficiently. Happy deploying!

--

--