output
During a build, Next.js will automatically trace each page and its dependencies to determine all of the files that are needed for deploying a production version of your application.
This feature helps reduce the size of deployments drastically. Previously, when deploying with Docker you would need to have all files from your package's dependencies installed to run next start. Starting with Next.js 12, you can leverage Output File Tracing in the .next/ directory to only include the necessary files.
Furthermore, this removes the need for the deprecated serverless target which can cause various issues and also creates unnecessary duplication.
How it Works
During next build, Next.js will use @vercel/nft to statically analyze import, require, and fs usage to determine all files that a page might load.
Next.js' production server is also traced for its needed files and output at .next/next-server.js.nft.json which can be leveraged in production.
To leverage the .nft.json files emitted to the .next output directory, you can read the list of files in each trace that are relative to the .nft.json file and then copy them to your deployment location.
Turbopack NFT extensions
Turbopack .nft.json files include fileHashes and symlinks extensions:
fileHashesis a parallel array with the same length and ordering asfiles. For example,fileHashes[0]is the hash forfiles[0]. A consumer can use the hash as a content identifier for caching or deduplicating traced assets.symlinksmaps indexes in the siblingfilesarray to their immediate targets. Whensymlinksis present, files without a corresponding entry can be assumed to be normal files or directories.
Traces that use additional roots also include the additionalRoots extension:
additionalRootsis an ordered list of named source roots. Each root has its ownfiles,fileHashes, andsymlinkslists. Itspathis relative to the directory containing the.nft.jsonfile and identifies the source location on the build machine. Names are guaranteed to be valid directory names.
Automatically Copying Traced Files
Next.js can automatically create a standalone folder that copies only the necessary files for a production deployment including select files in node_modules.
To leverage this automatic copying you can enable it in your next.config.js:
module.exports = {
output: 'standalone',
}This will create a folder at .next/standalone which can then be deployed on its own without installing node_modules.
On Windows, creating directory symlinks can require elevated privileges or Developer Mode. If standalone generation must fall back to a junction point, Windows stores an absolute target and that particular output is not relocatable.
Additionally, a minimal server.js file is also output which can be used instead of next start. This minimal server does not copy the public or .next/static folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the standalone/public and standalone/.next/static folders manually, after which server.js file will serve these automatically.
To copy these manually, you can use the cp command-line tool after you next build:
cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/To start your minimal server.js file locally, run the following command:
node .next/standalone/server.jsGood to know:
- If your project needs to listen to a specific port or hostname, you can define
PORTorHOSTNAMEenvironment variables before runningserver.js. For example, runPORT=8080 HOSTNAME=0.0.0.0 node server.jsto start the server onhttp://0.0.0.0:8080.
Environment variable files
When next build loads a .env or .env.production file, standalone output includes a copy of it in .next/standalone. At runtime, server.js reads these copies as defaults: environment variables set when the server starts take precedence, and any variable you do not set falls back to the copied value.
Other files the build loads, such as .env.local and .env.production.local, are not copied. Their values still apply to build-time work, like prerendered pages and inlined NEXT_PUBLIC_ variables, but server code running at request time only sees them if you set them when the server starts.
Since the copied files ship with the standalone output, keep only non-secret defaults in them and provide secrets as environment variables when you start server.js, for example from your hosting platform's environment settings or a secret manager. The Docker example follows this approach by leaving .env out of the build context with .dockerignore.
This copy is separate from file tracing, so outputFileTracingExcludes does not remove these files. To remove them, delete them after next build:
rm -f .next/standalone/.env .next/standalone/.env.productionGood to know: Deleting the files also removes their fallback values, so set every variable the server needs at runtime. When
outputFileTracingRootpoints above the project directory, the files are copied relative to that root, for example.next/standalone/packages/web-app/.env.
Caveats
- While tracing in monorepo setups, the project directory is used for tracing by default. For
next build packages/web-app,packages/web-appwould be the tracing root and any files outside of that folder will not be included. To include files outside of this folder you can setoutputFileTracingRootin yournext.config.js.
const path = require('path')
module.exports = {
// this includes files from the monorepo base two directories up
outputFileTracingRoot: path.join(__dirname, '../../'),
}- There are some cases in which Next.js might fail to include required files, or might incorrectly include unused files. In those cases, you can leverage
outputFileTracingIncludesandoutputFileTracingExcludesrespectively innext.config.js. Each option accepts an object whose keys are route globs (matched with picomatch against the route path, e.g./api/hello) and whose values are glob patterns resolved from the project root that specify files to include or exclude in the trace.
Good to know: In a monorepo,
project rootrefers to the Next.js project root (the folder containing next.config.js, e.g., packages/web-app), not necessarily the monorepo root.
module.exports = {
outputFileTracingExcludes: {
'/api/hello': ['./un-necessary-folder/**/*'],
},
outputFileTracingIncludes: {
'/api/another': ['./necessary-folder/**/*'],
'/api/login/\\[\\[\\.\\.\\.slug\\]\\]': [
'./node_modules/aws-crt/dist/bin/**/*',
],
},
}Using a src/ directory does not change how you write these options:
- Keys still match the route path (
'/api/hello','/products/[id]', etc.). - Values can reference paths under
src/since they are resolved relative to the project root.
module.exports = {
outputFileTracingIncludes: {
'/products/*': ['src/lib/payments/**/*'],
'/*': ['src/config/runtime/**/*.json'],
},
outputFileTracingExcludes: {
'/api/*': ['src/temp/**/*', 'public/large-logs/**/*'],
},
}You can also target all routes using a global key like '/*':
module.exports = {
outputFileTracingIncludes: {
'/*': ['src/i18n/locales/**/*.json'],
},
}These options are applied to server traces and do not affect routes that do not produce a server trace file:
- Edge Runtime routes are not affected.
- Fully static pages are not affected.
They also do not affect the .env and .env.production files that standalone output copies. See Environment variable files.
Standalone output also copies the files in the production server trace (.next/next-server.js.nft.json). For this trace, exclude keys are matched against the name next-server instead of a route path, so route globs that start with a slash, such as '/*', do not apply to it. To exclude files from this trace, use the 'next-server' key in outputFileTracingExcludes. This key is only supported for excludes:
module.exports = {
outputFileTracingExcludes: {
// Route traces
'/*': ['./scripts/**/*'],
// Production server trace
'next-server': ['./scripts/**/*'],
},
}In monorepos or when you need to include files outside the app folder, combine outputFileTracingRoot with includes:
const path = require('path')
module.exports = {
// Trace from the monorepo root
outputFileTracingRoot: path.join(__dirname, '../../'),
outputFileTracingIncludes: {
'/route1': ['../shared/assets/**/*'],
},
}Good to know:
- Prefer forward slashes (
/) in patterns for cross-platform compatibility.- Keep patterns as narrow as possible to avoid oversized traces (avoid
**/*at the repo root).
Common include patterns for native/runtime assets:
module.exports = {
outputFileTracingIncludes: {
'/*': ['node_modules/sharp/**/*', 'node_modules/aws-crt/dist/bin/**/*'],
},
}