Next.js in production
Building for production
-
npm ciInstalls the dependencies exactly as listed in the package-lock.json file, after first deleting any existing node_modules directory. This is the recommended way to install dependencies on a production server, because every installation gets exactly the same versions.
-
"scripts": { "dev": "next dev", "build": "next build", "start": "next start" }The scripts your package.json file needs: build to build the site and start to run the production server. The other commands on this page use them.
-
npm run buildRuns next build, which creates a version optimized for production in the .next directory. At the end of the build, the list of routes is shown: ○ marks a static page generated in advance, and ƒ marks a dynamic page rendered on every request.
-
npx next build --debugA build with verbose output, which also shows the rewrites, redirects, and headers settings. Useful when the build fails or when a setting isn't picked up.
-
npx next build --webpackBuilds with Webpack instead of Turbopack, which is the default. Suited to a project that depends on Webpack settings or plugins.
-
NODE_ENV=productionWhen the NODE_ENV variable isn't set, Next.js sets it to production for every command except next dev, so next build and next start run in production mode. The allowed values are production, development, and test.
-
.next/cacheThe build cache Next.js keeps from one build to the next. When the directory is kept between deployments, the next build is faster.
-
npx next infoShows the system details and the versions of Node.js, npm, next, and react, as well as the output setting. Useful before you report an issue.
Starting with next start
-
npm run startRuns next start, the Next.js production server, which supports every feature. By default, the server listens on port 3000 on all interfaces (0.0.0.0). Run npm run build first.
-
npm run start -- -p 4000Starts the server on a different port, 4000 in the example. With npm run, write -- before the options, so npm passes them on to next.
-
PORT=4000 npm run startSets the port in the PORT environment variable. You can't set PORT in a .env file, because the server starts before the .env files are loaded.
-
npm run start -- -H 127.0.0.1The server listens only on the local address, so the port isn't reachable from the internet, and the Nginx server in front of it passes the requests to it. This is the right setting behind a reverse proxy.
-
npm run start -- --keepAliveTimeout 70000Sets, in milliseconds, how long an idle connection stays open. Behind a load balancer or proxy, set a value higher than its keep-alive timeout, otherwise Node.js closes connections the proxy is still trying to use, and visitors get errors.
Standalone mode
-
module.exports = { output: 'standalone', }A setting in the next.config.js file: the build creates the .next/standalone directory with only the files that are needed, including the required part of node_modules, and a minimal server.js file that replaces next start. You can deploy the directory without installing node_modules.
-
cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/server.js doesn't include the public and .next/static directories. Once you copy them, it serves them itself. Run the command after every build, otherwise the CSS, JavaScript, and image files return 404.
-
node .next/standalone/server.jsStarts the minimal standalone server instead of next start.
-
PORT=3000 HOSTNAME=127.0.0.1 node .next/standalone/server.jsSets the port and the listening address in the PORT and HOSTNAME environment variables. With 127.0.0.1, the server listens only locally, behind Nginx.
-
rm -f .next/standalone/.env .next/standalone/.env.productionThe build copies the .env and .env.production files into the standalone directory, and server.js uses their values by default. Variables set when the server starts take precedence over them. Pass passwords and keys as environment variables at startup, not in files that ship with the build output. After you delete the files, set every variable the server needs at startup.
-
outputFileTracingRoot: path.join(__dirname, '../../'),In a monorepo: sets the directory from which Next.js collects files for the standalone output, two levels above the project in the example. Without this setting, files outside the project directory aren't included.
Environment variables
-
NEXT_PUBLIC_API_URL=https://api.example.comA variable with the NEXT_PUBLIC_ prefix is also available in the browser: its value is written into the JavaScript code at next build time. A change to it takes effect only after a rebuild, so never keep secrets in such a variable.
-
process.env.DB_PASSA variable without the NEXT_PUBLIC_ prefix is available only on the server side and isn't sent to the browser. On a page rendered on every request, for example after await connection(), the value is read at runtime, so the same build runs in several environments with different values.
-
.env.production.localThe lookup order for a variable: process.env, then .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV), and finally .env. The first value found wins. On a production server, NODE_ENV is production, so the .env.production.local file takes precedence over .env.production and .env. When NODE_ENV is test, the .env.local file isn't loaded.
-
process.env[varName]Dynamic access to a variable, through another variable or through a copy of process.env, isn't written into the code at build time, even when the name starts with NEXT_PUBLIC_. In code that runs in the browser, write the full name, for example process.env.NEXT_PUBLIC_API_URL.
-
BASE_URL=https://example.com API_URL=$BASE_URL/apiIn .env files, you can reference another variable with $. To write the $ character itself in a value, write \$.
Process management: PM2 and systemd
-
pm2 start "npm run start" --name webStarts next start through PM2, which runs the site in the background and restarts it if it crashes. You use the name web later in the restart and logs commands.
-
PORT=3000 HOSTNAME=127.0.0.1 pm2 start .next/standalone/server.js --name webStarts the standalone server through PM2, with a port and a local listening address.
-
pm2 restart web --update-envRestarts the site after a new build, and loads changed environment variables too. Without --update-env, the process keeps the variables that were set when it first started.
-
pm2 saveSaves the process list, so PM2 starts the site again after a server reboot. Set up automatic startup with pm2 startup first.
-
pm2 logs web --lines 100Shows the last 100 lines of the site's log and keeps showing new lines.
-
[Unit] Description=Next.js app After=network.target [Service] Type=simple User=deploy WorkingDirectory=/var/www/app Environment=NODE_ENV=production Environment=PORT=3000 Environment=HOSTNAME=127.0.0.1 ExecStart=/usr/bin/node .next/standalone/server.js Restart=on-failure [Install] WantedBy=multi-user.targetAn alternative to PM2: a systemd unit in the /etc/systemd/system/nextjs.service file. The site runs as a regular user, not as root. In ExecStart, write the full path to node, which the which node command shows. When Node.js is installed with nvm, the path is different.
-
sudo systemctl daemon-reload && sudo systemctl enable --now nextjsLoads the new unit file, enables automatic startup when the server boots, and starts the site right away.
-
sudo journalctl -u nextjs -fShows the site's log in real time, including startup errors. Press Ctrl+C to exit the view.
-
sudo systemctl restart nextjsRestarts the site after a new build. When the server receives the SIGTERM or SIGINT signal, Next.js finishes the requests in progress and the tasks scheduled with after() before it exits.
Nginx as a reverse proxy
-
location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; 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; }Nginx receives the requests from the internet, handles the SSL certificate, and passes them to the site on the local port. This way, Nginx also deals with malformed requests, slow connections, size limits, and rate limiting, and the Next.js server is free to render the pages.
-
location /_next/static/ { alias /var/www/app/.next/static/; add_header Cache-Control "public, max-age=31536000, immutable"; access_log off; }Serves the JavaScript and CSS files directly from Nginx, with long browser caching. The file names in this directory include a hash, so every build creates new names, and a one-year cache is safe. It's the same header Next.js sends for these files itself.
-
proxy_buffering off;Turns off response buffering in Nginx, so streaming and Suspense reach the visitor gradually and not only when the page has finished rendering. Add it in the site's location block.
-
async headers() { return [{ source: '/:path*{/}?', headers: [{ key: 'X-Accel-Buffering', value: 'no' }], }] },An alternative in next.config.js: the X-Accel-Buffering: no header asks Nginx not to buffer the site's responses, so streaming works without any change to the Nginx settings.
-
compress: false,By default, next start compresses responses with gzip. When Nginx handles compression, for example so you can switch to brotli, turn off Next.js compression in the next.config.js file. When neither of them compresses the responses, traffic volume grows.
-
curl -sI -H 'Accept-Encoding: gzip' https://example.com/ | grep -i content-encodingChecks whether the response is compressed, and with which method, based on the Content-Encoding header.
Caching and ISR
-
export const revalidate = 3600ISR in a page file: the page is generated in advance and served from the cache, and after an hour, the next request still gets the cached version while Next.js generates a new version in the background. A long interval is recommended, for example an hour rather than a second.
-
revalidatePath('/posts')Invalidates the cache for a path immediately, for example from a Server Action after a post is published. The page is generated again on the next request.
-
revalidateTag('posts', 'max')Invalidates the cache for all the data tagged posts, for example a fetch with next: { tags: ['posts'] }. Suited to data that appears on several pages.
-
curl -sI https://example.com/blog | grep -i x-nextjs-cacheThe x-nextjs-cache header shows where the page came from: HIT from the cache, STALE from the cache while a new version is generated, MISS rendered just now, and REVALIDATED generated again after the cache was invalidated.
-
NEXT_PRIVATE_DEBUG_CACHE=1An environment variable that logs every ISR cache hit and miss in the server log. Useful for testing with npm run build and npm run start before you deploy to the server.
-
module.exports = { cacheHandler: require.resolve('./cache-handler.js'), cacheMaxMemorySize: 0, }By default, the cache is kept in memory (up to 50MB) and on the disk of each instance separately. When the site runs on several instances, set up a shared cache handler, for example in Redis, and turn off the in-memory cache. The file implements get, set, revalidateTag, and resetRequestCache.
-
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=your-generated-key npm run buildWith several instances, every server needs the same encryption key for Server Actions, otherwise the Failed to find Server Action error appears. The key is a base64 value of 16, 24, or 32 bytes, for example the output of openssl rand -base64 32, and you keep it so every build uses it.
-
deploymentId: process.env.DEPLOYMENT_VERSION,A deployment ID in the next.config.js file. When a visitor with an earlier version of the site sends a request to a server running a new version, Next.js detects the mismatch and reloads the page in full.
Image optimization
-
npm i sharpThe next/image component resizes and converts images on the server with no extra configuration under next start, using the sharp package. When the sharp installation fails, the error Install sharp to Use Built-In Image Optimization appears, and you install the package again.
-
npm install --cpu=wasm32 sharpInstalls the WebAssembly version of sharp, when the regular version can't be built on the system.
-
.next/cache/imagesThe directory where the optimized images are stored. There's no mechanism to invalidate their cache, so to replace an image, delete the files in the directory or rename the image.
-
images: { minimumCacheTTL: 2678400, },The minimum cache time in seconds for an optimized image, 31 days in the example. In practice, the higher value applies: this setting or the Cache-Control header of the original image. The default is 4 hours, and since there's no mechanism to invalidate the image cache, the documentation recommends a low value.
-
images: { unoptimized: true, },Turns off image optimization on the server, while the other benefits of next/image remain. Suited to images that are already resized in advance.
Static export
-
module.exports = { output: 'export', }With this setting, npm run build creates the out directory with HTML, CSS, and JavaScript files, one HTML file per route. Upload the contents of the directory to any web server, and you don't need Node.js on the server.
-
trailingSlash: true,Generates each page as a directory with index.html, for example /about/index.html instead of about.html, and links end with /. This setting is convenient on a regular web server.
-
location / { try_files $uri $uri.html $uri/ =404; }An Nginx setting for a site built as a static export: the /about URL is served from the about.html file. The site's root path points to the out directory.
-
images: { loader: 'custom', loaderFile: './my-loader.ts', },A static export has no image optimization on the server. To keep using next/image, set up a loader that builds URLs for an external image service, or turn optimization off with unoptimized.
Docker
-
docker build -t nextjs-app .Builds an image from the Dockerfile in the project. The official Next.js Docker example uses standalone mode, so the image includes only the files needed to run the site.
-
docker run -d --name nextjs --restart unless-stopped -p 127.0.0.1:3000:3000 --env-file ./prod.env nextjs-appRuns the site in a container, with a port that's available only on the local address behind Nginx, and with the server's environment variables from a file. NEXT_PUBLIC_ variables are already set when the image is built.
Common problems
-
sudo ss -ltnp 'sport = :3000'The EADDRINUSE: address already in use error means another process is already listening on the port. The command shows which process is listening on port 3000, usually an earlier copy of the site that's still running. The output also shows the listening address: 127.0.0.1:3000 means the port isn't open to the internet.
-
npm run build && npm run startThe Could not find a production build error means the server was started without a build, or from a different directory. Run the build and then the server, from the same directory.
-
NODE_OPTIONS=--max-old-space-size=4096 npm run buildThe JavaScript heap out of memory error during the build: raises the Node.js memory limit, to 4096MB in the example. The value should leave memory for the other services on the server. For a server with 2GB of memory, the Node.js documentation suggests 1536.
-
npx next build --experimental-debug-memory-usageA build that prints memory usage as it runs, so you can find the stage that uses the most. When memory usage gets close to the limit, a heap snapshot is saved.
-
curl -I http://127.0.0.1:3000When Nginx returns 502 Bad Gateway, first check that the site responds on the local port. When there's no response, the site isn't running or is listening on a different port from the one in proxy_pass.
-
ls .next/standalone/.next/staticWhen the page loads without styling and _next/static files return 404 in standalone mode, the static directory wasn't copied after the build. Copy public and .next/static to the standalone directory and restart.
No matching commands.
There are three main ways to run a Next.js site on your own server. next start runs the site from the project directory and supports every feature. Standalone mode supports the same features and creates a small directory with server.js that you can copy to the server and run without installing the dependencies. A static export creates only HTML files that any web server can serve, but without the features that need a server: Server Actions, ISR, cookies, rewrites, redirects, and headers from next.config.js, Proxy (formerly Middleware), and image optimization on the server. Manage the process with PM2 or systemd, so the site comes back up after a crash and after a reboot.
The Next.js server shouldn't be exposed directly to the internet. Run it on 127.0.0.1, with Nginx in front of it receiving the requests on ports 80 and 443. More Nginx settings are on the Nginx cheat sheet. In the firewall, open only the web ports and SSH, with UFW or firewalld, and not port 3000. To run the site in a container, see the Docker commands and Docker Compose commands.
When the site runs on several instances, three things need to match across them: a shared cache for pages and ISR, the same encryption key for Server Actions, and the same build on every instance. On a single instance with a persistent disk, the cache works with no extra configuration. The domain names, paths, and ports on this page are examples, so replace them with your site's values.
On a Node.js VPS, the environment is ready in advance: Node.js is installed and configured, and you get full root access over SSH, so you build your Next.js site, start it with PM2, and set up a reverse proxy in front of it. A site built as a static export can be uploaded to any of our web hosting plans, with no need for Node.js on the server.
Next.js in production FAQ
Can I run a Next.js site on a VPS with every feature?
Yes. next start and standalone mode support every Next.js feature, including Server Actions, ISR, Proxy, and image optimization. Run the site as a Node.js process behind Nginx, manage it with PM2 or systemd, and every setting stays fully under your control.
What's the difference between next start and standalone mode?
next start runs the site from the project directory, with all the dependencies in node_modules. Standalone mode, which you turn on with the output: 'standalone' setting, creates the .next/standalone directory with only the files that are needed and a server.js file, so the deployment is smaller and doesn't require installing dependencies on the server. In standalone mode, copy the public and .next/static directories after every build.
Why doesn't a change to a NEXT_PUBLIC_ variable show up on the site?
Variables that start with NEXT_PUBLIC_ are written into the JavaScript code at next build time. That's why a change to the value takes effect only after you rebuild and restart the site. Variables without the prefix are read on the server side, and a new value takes effect when the process restarts, for example with pm2 restart and the --update-env option.
Can I upload a Next.js site to a web hosting plan?
Yes. A Next.js site built as a static export can be uploaded to any of our web hosting plans. With the output: 'export' setting, the build creates the out directory with HTML, CSS, and JavaScript files, and you upload the contents of the directory like any static site. A static export doesn't include features that need a server, such as Server Actions and ISR. For a site that needs them, a Node.js VPS is the right fit.
How do I update content on a Next.js site without rebuilding the whole site?
With ISR. Set a revalidation time on the page, for example export const revalidate = 3600, and the page is generated again in the background at most once an hour, while visitors keep getting the cached version quickly. For an immediate update, for example after you publish a post, call revalidatePath or revalidateTag, and the page is generated again on the next request.