# Next.js Standalone Output: Build, Run and Fix It

How Next.js standalone output works: what lands in .next/standalone, which folders to copy, how env files behave, monorepo paths, systemd and PM2 setups, and fixes for common errors.

By Waseem Anjum · Published 2026-11-27 · https://fabwaseem.com/blog/nextjs-standalone-output

> **TL;DR:** Set output: 'standalone', run next build, then copy .next/static and public next to the generated server.js and start it with node server.js. Copied .env files act as defaults, so keep secrets in the server environment. In monorepos server.js is nested under the app path. Set HOSTNAME=0.0.0.0 in containers and SuccessExitStatus=143 under systemd.

Next.js standalone output (`output: 'standalone'` in `next.config`) makes `next build` write a self-contained server to `.next/standalone`, with only the `node_modules` files your app needs. Copy `public` and `.next/static` into that folder, then start it with `node server.js`. No `npm install` is needed on the server.

The examples below use Next.js 16.4. They cover the folder layout, environment variables, monorepos, running under systemd or PM2, and the errors that show up most often.

## What is Next.js standalone output?

Next.js standalone output is a deployment folder that Next.js assembles from its file trace. During `next build`, it analyzes `import`, `require` and `fs` usage to find the files each route needs, then copies them into `.next/standalone` together with a minimal `server.js` that replaces `next start`.

The [official `output` reference](https://nextjs.org/docs/app/api-reference/config/next-config-js/output) describes the tracing step. What matters when you deploy is what ends up in the folder and what does not:

| Item | In `.next/standalone`? | What you do |
| --- | --- | --- |
| `server.js` | Yes | Run it with Node.js |
| Traced `node_modules` | Yes | Nothing |
| Server build output | Yes | Nothing |
| `.env`, `.env.production` | Yes, if the build loaded them | Keep secrets out of them |
| `.next/static` (JS, CSS) | **No** | Copy it, or serve it from a CDN |
| `public/` | **No** | Copy it, or serve it from a CDN |
| `.env.local`, `.env.production.local` | No | Set those variables on the server |

![Next.js standalone folder layout: server.js and traced node_modules are included, while public and .next/static must be copied](https://res.cloudinary.com/wasicloudinary/image/upload/v1795752995/fabwaseem/projects/jka8hvdhfbaubjf45ex4.jpg)

## How do you build and run Next.js standalone output?

Add `output: 'standalone'` to your config, run `next build`, copy the two asset folders next to `server.js`, and start the server with Node.js. Next.js 16.4 requires Node.js 20.9 or later.

### Step 1: enable standalone output

```ts
// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
};

export default nextConfig;
```

### Step 2: build and copy the assets

On macOS and Linux:

```bash
npx next build
cp -r public .next/standalone/
cp -r .next/static .next/standalone/.next/
```

### Step 3: start the server

`PORT` defaults to `3000` and `HOSTNAME` to `0.0.0.0`:

```bash
PORT=8080 HOSTNAME=127.0.0.1 node .next/standalone/server.js
```

Set these two in the process environment. A `PORT` or `HOSTNAME` that exists only in a copied `.env` file does not change the listen address, because `server.js` reads both before Next.js loads env files.

In PowerShell, set the variables first: `$env:PORT=8080; node .next/standalone/server.js`.

### A copy script that works on Windows, macOS and Linux

`cp -r` behaves differently across shells, so a small Node script is safer in `package.json`. It takes the app's path inside a monorepo as an optional argument.

```js
// scripts/copy-standalone.mjs
import { cpSync, existsSync } from "node:fs";
import path from "node:path";

// Monorepo: pass the app path, for example "apps/web"
const serverDir = path.join(".next", "standalone", process.argv[2] ?? "");

if (!existsSync(path.join(serverDir, "server.js"))) {
  throw new Error(`No server.js in ${serverDir}. Check output: "standalone".`);
}

cpSync(".next/static", path.join(serverDir, ".next", "static"), {
  recursive: true,
});

if (existsSync("public")) {
  cpSync("public", path.join(serverDir, "public"), { recursive: true });
}

console.log(`Ready: node ${path.join(serverDir, "server.js")}`);
```

```json
{
  "scripts": {
    "build": "next build && node scripts/copy-standalone.mjs",
    "start": "node .next/standalone/server.js"
  }
}
```

These two scripts are for a single app. In a monorepo, add the app path to both, for example `node scripts/copy-standalone.mjs apps/web`.

If you deploy only the folder, put migrations and other pre-start tasks in your deploy step. Running `node server.js` directly does not trigger npm's `prestart` script.

Build on the same operating system and CPU architecture as the server, or inside a container that matches it. The traced `node_modules` can include platform-specific binaries, such as the ones [sharp installs](https://sharp.pixelplumbing.com/install/) for image processing.

For containers, the [official Docker example](https://github.com/vercel/next.js/tree/canary/examples/with-docker) copies the same three paths into the final stage. The [production Next.js Dockerfile guide](https://fabwaseem.com/blog/nextjs-dockerfile) walks through that setup, including health checks and a non-root user.

## How do environment variables work in standalone mode?

Server code in standalone mode reads variables from the environment you start `server.js` with. If the build loaded `.env` or `.env.production`, copies ship in the folder and act as defaults. `NEXT_PUBLIC_` variables are inlined into the browser bundle at build time, so changing them requires a rebuild.

The rules, from the Next.js docs:

- Variables set when the server starts **take precedence** over the copied `.env` files.
- `.env.local` and `.env.production.local` are **not copied**. They still apply during the build, but request-time code only sees those values if you set them on the server.
- `outputFileTracingExcludes` does **not** remove the copied `.env` files.

The copied files are the part to watch: a secret in `.env` travels with your build artifact. Keep non-secret defaults there, or delete the copies after the build. In a monorepo they sit under the app's subfolder, such as `.next/standalone/apps/web/.env`.

```bash
rm -f .next/standalone/.env .next/standalone/.env.production
```

Deleting them also removes their fallback values, so set every variable the server needs when you start it.

To make a route read a value at request time instead of during prerendering, call [`connection()`](https://nextjs.org/docs/app/guides/environment-variables) first:

```ts
// app/api/config/route.ts
import { connection } from "next/server";

export async function GET() {
  await connection();
  return Response.json({ region: process.env.APP_REGION ?? "unset" });
}
```

Your `next.config` is different: it is read during `next build` and serialized into `server.js`. A config value computed from an environment variable keeps its build-time value.

![Next.js standalone environment variables: copied .env files are defaults, server variables win, NEXT_PUBLIC values are fixed at build time](https://res.cloudinary.com/wasicloudinary/image/upload/v1795752997/fabwaseem/projects/z8jsqwgrja73g0rukj5f.jpg)

## How does Next.js standalone work in a monorepo?

In a monorepo, the standalone folder mirrors the path from the tracing root to your app. With an app in `apps/web`, the server is at `.next/standalone/apps/web/server.js`, while shared `node_modules` sit higher up in `.next/standalone`. The static and public folders go beside that nested `server.js`.

Set the tracing root explicitly to the repository root, so the build does not depend on which lockfile Next.js finds:

```ts
// apps/web/next.config.ts
import path from "node:path";
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
  outputFileTracingRoot: path.join(__dirname, "../../"),
};

export default nextConfig;
```

Then build, copy and start from the app folder:

```bash
npx next build
node scripts/copy-standalone.mjs apps/web
node .next/standalone/apps/web/server.js
```

Deploy the whole `.next/standalone` directory, not only the `apps/web` subfolder, or the server loses its dependencies. In that case the paths on your server are `apps/web/server.js` plus `node_modules` at the top.

## How do you include files missing from the standalone build?

Use `outputFileTracingIncludes` when a file your code reads at runtime is not in `.next/standalone`. Keys are route globs, and values are file globs resolved from the Next.js project folder. Typical candidates are templates, locale files and native assets whose paths are built dynamically.

```js
// next.config.js
module.exports = {
  output: "standalone",
  outputFileTracingIncludes: {
    "/api/invoice": ["./templates/**/*"],
  },
  outputFileTracingExcludes: {
    "/*": ["./test-fixtures/**/*"],
  },
};
```

Keep these details in mind:

- The [generated `server.js`](https://github.com/vercel/next.js/blob/v16.4.6/packages/next/src/build/utils.ts) changes the working directory to its own folder, so build file paths with `process.cwd()` relative to the app root.
- Route include and exclude options apply to server traces. Fully static pages and Edge routes are not affected.
- To exclude files from the production server trace, use the special `next-server` key in `outputFileTracingExcludes`. Route globs such as `'/*'` do not apply to that trace.

## How do you run a Next.js standalone server with systemd or PM2?

Copy the prepared standalone folder to the server and let a process manager run `node server.js`, with a reverse proxy in front. Next.js [recommends a reverse proxy](https://nextjs.org/docs/app/guides/self-hosting) such as nginx instead of exposing the Node.js server directly, so bind to `127.0.0.1` when the proxy runs on the same machine.

### Prepare the server

Use one user to own the files and run the app. These examples use an existing `deploy` user. Create the folder once on the server:

```bash
sudo mkdir -p /srv/web
sudo chown deploy:deploy /srv/web
```

From your build machine, copy the contents of the prepared folder, including the hidden `.next` directory:

```bash
rsync -a .next/standalone/ deploy@server:/srv/web/
```

On the server, create `/etc/web.env` with your runtime variables, one `NAME=value` per line, and let the `deploy` group read it:

```bash
sudo chown root:deploy /etc/web.env
sudo chmod 640 /etc/web.env
```

Then pick systemd or PM2, not both. To redeploy, run `rsync` again and restart the app with `sudo systemctl restart web` or `pm2 restart web`.

In a monorepo, the app lives in `/srv/web/apps/web`. Use that path for `WorkingDirectory` and the PM2 `cwd`.

### systemd

```ini
# /etc/systemd/system/web.service
[Unit]
Description=Next.js standalone server
After=network.target

[Service]
User=deploy
WorkingDirectory=/srv/web
Environment=PORT=3000 HOSTNAME=127.0.0.1
EnvironmentFile=/etc/web.env
ExecStart=/usr/bin/node server.js
Restart=on-failure
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target
```

The unit [fails to start if the environment file is missing](https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html). Check your Node.js path with `which node`, then run `sudo systemctl daemon-reload` and `sudo systemctl enable --now web`.

The `SuccessExitStatus=143` line matters. On `SIGTERM`, the [Next.js server](https://github.com/vercel/next.js/blob/v16.4.6/packages/next/src/server/lib/start-server.ts) closes and then exits with code 143. [systemd treats](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html) exit code 0 and a few termination signals as clean, but a numeric 143 is only clean if you list it.

### PM2

Install it with `npm install -g pm2`. PM2 does not read `/etc/web.env` by itself, so pass the file to Node.js with `--env-file`:

```js
// /srv/web/ecosystem.config.cjs
module.exports = {
  apps: [
    {
      name: "web",
      cwd: "/srv/web",
      script: "server.js",
      node_args: "--env-file=/etc/web.env",
      env: { PORT: 3000, HOSTNAME: "127.0.0.1" },
    },
  ],
};
```

The `.cjs` extension keeps `module.exports` valid even if the copied `package.json` sets `"type": "module"`. As the `deploy` user, run `pm2 start ecosystem.config.cjs`, then `pm2 startup` (and the command it prints) and `pm2 save` so the app [returns after a reboot](https://pm2.keymetrics.io/docs/usage/startup/).

### Keep-alive timeouts behind a load balancer

The server's keep-alive timeout should be longer than the downstream proxy's, otherwise the proxy can reuse a connection Node.js has closed. With `next start` you pass `--keepAliveTimeout`. With standalone, `server.js` reads the `KEEP_ALIVE_TIMEOUT` variable in milliseconds, so set it, for example `KEEP_ALIVE_TIMEOUT=70000` behind a 60-second proxy timeout.

If you would rather use a platform, [self-hosting Next.js with Coolify](https://fabwaseem.com/blog/self-host-nextjs-with-coolify) handles the proxy and deploys, and [Cloudflare Tunnel with Docker Compose](https://fabwaseem.com/blog/cloudflare-tunnel-docker-compose) publishes the app without open ports. When you run several instances, give them a shared cache, as covered in the [`use cache` guide](https://fabwaseem.com/blog/nextjs-use-cache).

## How do you fix common Next.js standalone errors?

Most standalone failures come from a handful of causes: assets that were not copied, the wrong listen address, files missing from the trace, binaries built for another platform, and a tracing root that does not match your repository. Match your message below.

### "next start" does not work with "output: standalone"

```text
⚠ "next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.
```

Change the start command to `node .next/standalone/server.js` (or the nested monorepo path). To keep using `next start`, remove `output: 'standalone'`.

### CSS, JavaScript or images return 404

The server runs, but the page has no styles. `.next/static` or `public` is missing next to `server.js`. Copy them to exactly `<server folder>/.next/static` and `<server folder>/public`.

### The server is unreachable in Docker

`server.js` listens on `process.env.HOSTNAME`, and [Docker sets `HOSTNAME`](https://docs.docker.com/engine/containers/run/) in Linux containers to the container's hostname. Override it in the Dockerfile, as the official example does:

```dockerfile
ENV HOSTNAME=0.0.0.0
```

### Could not find the Next.js package

```text
Error: Could not find the Next.js package (next/package.json)
```

With Turbopack in a monorepo, one cause is a root that is too narrow: `next` is installed above `outputFileTracingRoot`. Point it at the repository root. A related build warning says traced files "were not included in the standalone output" because they are outside that root, and the fix is the same.

### Could not load the "sharp" module

```text
Could not load the "sharp" module using the linux-x64 runtime
```

The traced `node_modules` does not contain a native binary that matches the server's operating system, CPU or C library. Install dependencies and build on the same platform as the runtime (glibc and musl differ), keep optional dependencies enabled, and rebuild. The [sharp installation guide](https://sharp.pixelplumbing.com/install/) covers cross-platform installs.

### Cannot find module with a custom server

Next.js does not trace custom server files, and the [custom server guide](https://nextjs.org/docs/app/guides/custom-server) says the two cannot be used together. One [symptom reported on Next.js 14.1.4](https://github.com/vercel/next.js/issues/64031) is `Cannot find module './bundle5'`. Use the generated `server.js`, or drop standalone output and deploy your custom server with full dependencies.

### EPERM: operation not permitted, symlink (Windows)

One [report on Next.js 14.2.8 with pnpm](https://github.com/vercel/next.js/issues/69858) hit this error, and the reporter got past it with an administrator terminal. Current docs note that directory symlinks can need Developer Mode, and that a build which falls back to a junction point cannot be moved to another location. Upgrade Next.js, enable Developer Mode or run the terminal as administrator, and build deployment artifacts on Linux when you can.

## Should you use standalone, next start or static export?

Use standalone when you run Node.js yourself and want a small artifact, such as a Docker image or a VPS release. Use the default output with `next start` when installing all dependencies is acceptable. Use static export only when the site needs no Node.js server at runtime.

| | Default | `standalone` | `export` |
| --- | --- | --- | --- |
| Start command | `next start` | `node server.js` | Any static file server |
| `node_modules` on server | Installed | Traced subset included | None |
| Server rendering and route handlers | Yes | Yes | No server at runtime |
| Static and public files | Served automatically | Copy them first | They are the output |
| Custom server | Possible | Not supported | Not applicable |
| Best for | Simple Node hosts | Containers, self-hosting | CDN-only sites |

Want your app moved to your own server without the trial and error? See [Next.js development services](https://fabwaseem.com/services/nextjs-development). For the full path from platform choice to a running deployment, read the [self-host Next.js guide](https://fabwaseem.com/guides/self-host-nextjs).

## Key takeaways

- `output: 'standalone'` creates `.next/standalone` with `server.js` and only the traced dependencies.
- Copy `.next/static` and `public` beside `server.js`, or serve them from a CDN.
- `.env` and `.env.production` can ship inside the folder; keep secrets in the server environment.
- In monorepos, `server.js` is nested under the app path, so set `outputFileTracingRoot` and deploy the whole folder.
- Set `HOSTNAME=0.0.0.0` in containers, and add `SuccessExitStatus=143` under systemd.

## Questions

### What does output: 'standalone' do in Next.js?

It makes next build create .next/standalone, a folder with a minimal server.js and only the traced files from node_modules. You can deploy that folder without installing dependencies, after copying public and .next/static into it.

### How do I run a Next.js standalone build?

Copy public and .next/static next to server.js, then run node .next/standalone/server.js. Set PORT and HOSTNAME as environment variables if you need something other than port 3000 on 0.0.0.0.

### Why does Next.js standalone return 404 for CSS and JavaScript?

The standalone folder does not include .next/static or public. Copy them to .next/static and public inside the folder that contains server.js, or serve them from a CDN.

### Can I use next start with output: standalone?

Not as intended. Next.js warns that next start does not work with the standalone configuration and tells you to run node .next/standalone/server.js. To keep next start, remove the output setting.

### Are .env files included in the standalone folder?

Copies of .env and .env.production are included when the build loads them, and they act as runtime defaults. .env.local and .env.production.local are not copied, so set those values in the server environment.

### Do I need Docker to use Next.js standalone output?

No. The folder runs anywhere a supported Node.js version is installed, for example under systemd or PM2 on a VPS. Build it on a matching operating system and CPU architecture.
