Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Static Export, Standalone Output, and Docker Deployment

Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.

~4 min readNext.js
#Next.js#Deployment#Docker#Build
3D illustration of static HTML cards beside a shipping container with a package cube inside

Quick Summary

next build has three output modes that are often confused because they all change .next. The default produces a hybrid build for a Next.js server. output: "standalone" produces that same server plus a minimal node_modules subset so a container can run it without installing dependencies. output: "export" produces a folder of static files with no server at all, which removes ISR, Server Actions, middleware, dynamic route handlers, and image optimisation.

Choosing wrongly is expensive. An export cannot serve revalidate, so a site that relies on ISR must be standalone behind a Node process. A standalone image that omits .next/static and public loads HTML with no CSS — the second most common deployment failure after a missing HOSTNAME.

Docker is the usual target. A three-stage build (deps, builder, runner) with output: "standalone" yields an image around 150–250 MB that starts in under a second and needs only node server.js.

Basic Syntax & Core Signatures

ts
// next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { output: "standalone", // or "export" images: { // required for "export": no server-side optimiser exists unoptimized: true, remotePatterns: [{ protocol: "https", hostname: "images.example.com" }], }, trailingSlash: true, // static hosts map /about to /about/index.html basePath: process.env.BASE_PATH || "", }; export default nextConfig;
dockerfile
# syntax=docker/dockerfile:1.7 FROM node:22-alpine AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM node:22-alpine AS builder WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . ENV NEXT_TELEMETRY_DISABLED=1 RUN npm run build FROM node:22-alpine AS runner WORKDIR /app ENV NODE_ENV=production ENV NEXT_TELEMETRY_DISABLED=1 ENV PORT=3000 ENV HOSTNAME=0.0.0.0 RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001 COPY --from=builder /app/public ./public COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static USER nextjs EXPOSE 3000 CMD ["node", "server.js"]
bash
# Static export: build output is the deployable artifact next build # writes ./out # serve it with any static host, and make sure the host rewrites unknown paths to 404.html

server.js inside the standalone folder reads PORT and HOSTNAME. Binding to the default localhost inside a container makes the port unreachable from outside the container, which looks like a crash loop in logs that show a successful start.

Key Comparison Table

FeatureDefault buildoutput: "standalone"output: "export"
Needs a Node serverYesYes (node server.js)No
node_modules required at runtimeYes, full installNo, pruned subsetNo
ISR / revalidateYesYesNo
Server ActionsYesYesNo
Middleware / proxy.tsYesYesNo
Route handlersAll methodsAll methodsGET only, build time
next/image optimisationYesYesNo, unoptimized: true
Dynamic routes without generateStaticParamsYesYesBuild error
Cookies, headers, sessionsYesYesNo
Deployment targetNode hostContainer, VM, Node hostCDN, S3, GitHub Pages, Netlify
Typical image sizen/a~150–250 MBn/a, static files only
Deploy targetRecommended outputWatch out for
VercelDefaultNothing; platform handles tracing
Docker on ECS or Cloud RunstandaloneCopy static and public; set HOSTNAME
KubernetesstandalonereadOnlyRootFilesystem breaks .next/cache
S3 + CloudFrontexportNo server features; trailingSlash
GitHub PagesexportbasePath for project pages, no rewrites
Nginx serving a Node appstandaloneProxy headers, health check path

Practical Edge Cases & Deep Dives

1. The image with no CSS

output: "standalone" copies traced server files, not .next/static or public — the docs say so, and it is still the most common bug. Without the copy, HTML returns 200 and the browser requests /_next/static/css/... which returns 404, so the page renders as unstyled HTML.

dockerfile
COPY --from=builder /app/public ./public COPY --from=builder /app/.next/static ./.next/static

Verify after deploying rather than after building:

bash
curl -s http://localhost:3000 | grep -o '/_next/static/[^"]*\.css' | head -1 | \ xargs -I{} curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000{}

2. sharp and the image optimiser in a pruned image

The standalone trace normally includes sharp, but when the optimiser is installed as an optional dependency of a platform-specific build, the traced copy can miss the binary. The symptom is Error: 'sharp' is required to be installed in standalone mode on the first image request. Two fixes: install sharp in the runner stage (RUN npm i sharp), or set images.unoptimized: true and serve pre-sized images.

3. Files that tracing cannot see

outputFileTracingIncludes exists because file tracing follows import statements, not runtime string paths. A route that reads a template from templates/email.html or a dictionary from locales/*.json at runtime will 404 only in production.

ts
const nextConfig: NextConfig = { output: "standalone", outputFileTracingIncludes: { "/api/report": ["./templates/**/*", "./locales/**/*"], }, };

4. Build-time environment in Docker

NEXT_PUBLIC_* values are compiled into the client bundle during npm run build inside the builder stage. Setting them with docker run -e does nothing for the client. Pass them as build args, or keep the value server-side and read it per request.

bash
docker build --build-arg NEXT_PUBLIC_SITE_URL=https://example.com -t app .

Also clear the build cache when a public variable changes, or the cached layer keeps the old value.

5. Static export limits that appear as build errors

With output: "export", a dynamic route without generateStaticParams fails the build with "Page ... is missing param ... which is required with output: export". That is a feature: the error names every route that cannot be prerendered. Route handlers must be GET and must not read request data at runtime; a POST handler in an exported build is simply unreachable. Plan for an external form endpoint or a third-party service for anything that writes.

tsx
// app/blog/[slug]/page.tsx — required for export export async function generateStaticParams() { const posts = await fetch("https://cms.example.com/posts").then((r) => r.json()); return posts.map((p: { slug: string }) => ({ slug: p.slug })); } export const dynamicParams = false; // 404 for anything not prerendered

6. Health checks, graceful shutdown, and .next/cache

A container orchestrator sends SIGTERM and expects the process to exit; server.js handles it, but in-flight ISR revalidation can be cut. Mount .next/cache as a writable volume if the image runs with a read-only root filesystem, otherwise every revalidation fails silently and pages stay stale. For the health check, use a real route (/api/health returning 200) rather than /, because a dynamic home page can be slow under cold start and the probe will restart a healthy container.

Finally, pin the base image. node:22-alpine moves under you between builds; node:22.11-alpine3.20 does not. A base-image change can alter the traced optional dependencies and turn a working image into one that fails on the first image request.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Page loads unstyled.next/static not copied into the imageAdd the COPY line, verify with curl
Container starts, port unreachableHOSTNAME left as localhostENV HOSTNAME=0.0.0.0
'sharp' is required in standalone modeOptional binary not tracedInstall sharp in the runner stage
Runtime file read 404s in production onlyFile tracing missed a runtime pathoutputFileTracingIncludes
Client uses the staging URL in productionNEXT_PUBLIC_* baked during buildBuild args, or read the value on the server
Export build fails on a dynamic routegenerateStaticParams missingAdd it, or set dynamicParams = false and accept 404s
POST endpoint returns 405 after exportStatic export has no serverMove the write to an external API
ISR silently stops after a dayRead-only .next/cacheMount a writable volume

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.