What is Nx generatePackageJson and what problem does it solve?

generatePackageJson is a build option on Nx's Node-oriented executors. When it is enabled, the build writes a package.json into the app's output directory that lists only the third-party packages that app uses. When the workspace has a supported lockfile, Nx also writes a pruned lockfile next to it, trimmed to the same dependency set with resolved versions preserved. Treat these files as a build artifact contract. The output directory becomes a self-contained install unit, so a deploy step can run a normal install inside it without ever seeing the workspace root.

This matters because an Nx workspace usually has one root package.json. That manifest is the union of every project's dependencies. An API service, a queue worker, a CLI and a frontend all add their packages to the same list. If you copy that root manifest into each service's image, you get three problems:

  • Installs are larger than they need to be. A worker that only talks to a message broker still installs the ORM, the PDF renderer and the frontend tooling used elsewhere.
  • The vulnerability surface is wider. Scanners flag every package in the image, including ones the service never loads. Each finding still has to be triaged.
  • Unrelated deploys are coupled. Bumping a dependency for one app changes the manifest and lockfile copied into every image. That invalidates cached install layers and forces rebuilds of services whose code did not change.

The engineers who benefit most are backend and platform engineers shipping several Node services from one workspace. Per-app manifests let each image reflect only what its own service needs.

Who should use generatePackageJson?

The option fits teams with a specific setup. Use it if your team matches these conditions:

  • Several deployable Node apps in one Nx workspace. These are API services, workers, scheduled jobs or CLIs, each shipped as its own container image or deploy artifact. The more the apps' dependency sets differ, the more pruning removes.
  • A single-version policy at the root. The workspace keeps one root package.json and one lockfile, and you want every app to use those versions without keeping per-app version lists.
  • Platform or DevOps engineers who own the image pipeline. Someone has to own the Dockerfiles, the CI verification and the cache configuration described below. The option produces artifacts, and someone has to consume and check them.
  • Security or compliance owners who triage scanner output per image. A pruned lockfile gives an exact, per-app list of what is installed, which narrows triage.

It is a poor fit in four cases:

  • Workspaces with a single app that uses nearly all root dependencies.
  • Frontend-only workspaces whose output is static assets with no runtime node_modules.
  • Teams that already use their package manager's own workspace deploy or prune command and are satisfied with it.

When should you use generatePackageJson?

Turn it on at the point where the deploy step needs to install dependencies for one app without the rest of the monorepo. Concretely:

  • When you build container images per app. The install stage of a multi-stage Dockerfile needs a manifest and lockfile scoped to that app. The generated files are exactly that input.
  • When you deploy unbundled or partially bundled Node output. If externals or native modules must be installed at deploy time, the app needs its own manifest listing them.
  • When unrelated dependency bumps are forcing rebuilds. If changing a package used by one service invalidates install layers for every service, per-app lockfiles break that coupling.
  • When scanner findings include packages a service never loads. Pruning removes them from the image, so they stop appearing in that image's report.
  • When you deploy to a platform that runs its own install. Some hosting targets run an install from a package.json in the uploaded directory. A pruned manifest keeps that install scoped to the app.

Hold off when the app is fully bundled with no externals, because there is nothing left to install. Also hold off when you do not yet have a CI step that installs and starts the built output. Without that step, inference gaps surface in production instead of in the pipeline.

How does generatePackageJson work?

At a high level, the build does four things in order:

  1. Builds the project graph. Nx analyzes source files across the workspace and records which projects import which workspace libraries and which npm packages.
  2. Collects the app's external dependencies. Starting from the app, Nx walks its edges, including edges through internal workspace libraries, and gathers every npm package reached.
  3. Writes the manifest. For each collected package, Nx takes the version from the root package.json and writes the result as package.json in the output directory. Entries in the app's own package.json, if it has one, are merged in.
  4. Prunes the lockfile. If the root lockfile is in a supported format, Nx copies the entries for those packages and their transitive npm dependencies into a lockfile in the output directory. It keeps resolved versions and integrity data and uses the same package manager format.

The result sits next to the compiled code. The deploy step then runs a frozen install there. The sections below cover each part in detail: how inference works, where it misses packages, how bundling changes the output, and how to consume and verify the files.

How does Nx infer which dependencies an app needs?

The answer comes from the Nx project graph. Nx statically analyzes the import and require statements in the app's source files and records an edge for every specifier it can resolve. When an import resolves to a workspace library, Nx follows that library's own imports as well. If api-gateway imports @acme/auth, and auth imports jsonwebtoken, then jsonwebtoken ends up in the gateway's manifest even though the app never names it. This transitive walk through internal libraries is why the output is usually correct without hand-curation. Libraries are a build-time concept, and their npm dependencies must appear wherever their code ships.

Nx does not choose versions itself. Each external node in the graph takes its version from the root package.json, so the generated manifest pins the versions the whole workspace already agreed on. The pruned lockfile is a subset of the root lockfile. It keeps the exact resolved versions and integrity data for the packages the app needs, including their transitive npm dependencies, and it is written in the workspace package manager's own format.

That gives you two guarantees. A frozen or CI-mode install succeeds, and that install resolves the same versions you tested against. It does not give you three things:

  • Automatic refresh. The pruned lockfile reflects the root lockfile at build time. A stale root lockfile produces a stale pruned one.
  • Coverage beyond the graph. It is only as accurate as the graph. Imports that static analysis cannot see are missing.
  • Support for every package manager. Support varies by package manager.

To enable it, set generatePackageJson: true in the options of the app's build target, alongside main, outputPath, and tsConfig. Check the option name and its availability against your Nx version and executor (webpack, esbuild, or tsc) before relying on it.

{
  "name": "api-gateway",
  "targets": {
    "build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "options": {
        "target": "node",
        "compiler": "tsc",
        "main": "apps/api-gateway/src/main.ts",
        "outputPath": "dist/apps/api-gateway",
        "tsConfig": "apps/api-gateway/tsconfig.app.json",

        "generatePackageJson": true
      }
    }
  }
}

An app's project.json build target with generatePackageJson enabled, which writes a pruned package.json and lockfile to the output path. Verify the executor name and option against your Nx version.

Where does dependency pruning miss packages, and how do you close the gaps?

Nx builds the generated manifest from the project graph, which comes from static analysis of import and require calls. Anything the code loads in a way the analyzer can't follow is left out, and the failure usually shows up at runtime in the deployed container, not at build time.

Blind spot Why inference misses it How to close the gap
Dynamic require(name) The specifier is computed at runtime Declare it in the app's own package.json
Config-named packages (ORM drivers, logging transports, plugins) The library loads them by string Declare it in the app's own package.json
Peer dependencies The host library expects them but your code never imports them Declare them explicitly
Native addons Resolved through bindings at load time Declare them, and rebuild inside the target image
CLI tools run via npx or exec They are not imported anywhere Declare them, or move the step to build time
Workspace libraries loaded by name No import edge in the graph Add the project to implicitDependencies

Put the app's own package.json dependency entries under a loose specifier rather than an exact version. Whether a loose specifier defers to the root version depends on your Nx version and executor, so confirm it in the generated output. Every extra you declare this way is something you have to maintain by hand. Nothing removes a stale entry after the code stops using it. Review these lists whenever drivers or plugins change.

Never patch the generated package.json in dist. Fix the root manifest or the project declaration instead. Hand edits are overwritten on the next build, and if they persist, they let one app quietly drift off the single-version policy.

Don't assume that patch-package patches, overrides/resolutions, workspace: protocol links, or private registry scoping in .npmrc survive pruning. Inspect the pruned lockfile and run a clean install against it before you trust it.

#!/usr/bin/env bash
set -euo pipefail

cat > apps/api/package.json <<'EOF'
{
  "name": "api",
  "dependencies": {
    "pg": "*",
    "pino-pretty": "*",
    "sharp": "*"
  }
}
EOF

jq '.implicitDependencies = ((.implicitDependencies // []) + ["api-plugins"] | unique)' \
  apps/api/project.json > /tmp/project.json && mv /tmp/project.json apps/api/project.json

npx nx build api
GEN=dist/apps/api/package.json   # adjust to your executor's outputPath

node -e '
const path = require("path");
const [root, gen] = process.argv.slice(1).map(p => require(path.resolve(p)));
for (const name of ["pg", "pino-pretty", "sharp"]) {
  const want = (root.dependencies || {})[name];
  const got = (gen.dependencies || {})[name];
  console.log(name, want === got ? "ok" : "MISMATCH", "root=" + want, "generated=" + got);
  if (want !== got) process.exitCode = 1;
}' package.json "$GEN"

Declaring analyzer-invisible dependencies with loose specifiers and an implicit dependency, then checking that the generated manifest resolves them to the root versions instead of assuming it does.

How do bundling choices change the generated package.json?

The bundler decides what ends up in the generated manifest. When it inlines a third-party package into the output file, that package is no longer resolved from node_modules at runtime, so Nx has no reason to list it. A fully bundled app can produce a package.json that contains only the packages you explicitly marked as external, and a lockfile pruned to match.

The risk comes from handling the same package two ways. Suppose pg is inlined but a library it depends on is external, or the reverse. You can end up with two copies of a module that relies on singleton state, such as an ORM's connection registry or instanceof checks across package boundaries. Or the manifest can omit a package that the bundle still requires. Mark a package and its dependency closure consistently, either all inlined or all external.

Keep these packages external:

  • Native modules (.node binaries such as bcrypt or sharp). They must be compiled or downloaded for the target platform during install.
  • Packages that read runtime files relative to __dirname, such as templates, WASM, or Prisma engines. Bundling moves the code but leaves the assets behind.
  • Packages loaded by name, including plugin systems, require(variable), and ORM dialect drivers. The bundler cannot see these imports statically.
Strategy Generated manifest Image install step Main risk
Fully bundled Near-empty Minimal or none Broken native, asset, or dynamic loads
Externals + pruned manifest Externals only Small, deterministic Inconsistent external marking
Unbundled All inferred deps Full production install Larger image, slower cold install

How do you build a minimal Docker image for an nx deploy node app?

The reference image uses three stages, and the boundary between them is the point of the design.

Builder stage. Copy the full workspace, install all dependencies, and run the Nx build for the target app. This stage needs the monorepo source, dev dependencies, and build tooling. None of that should reach production, so treat this stage as disposable.

Install stage. Start from a clean base image and copy only the app's dist directory: the bundle, the generated package.json, and the pruned lockfile. Run a frozen production install there, such as npm ci --omit=dev or your package manager's frozen-lockfile equivalent. A frozen install fails if the manifest and lockfile disagree, so it catches a stale or broken prune instead of silently resolving new versions.

Runtime stage. Copy the installed node_modules and the bundle into a minimal Node base image. Set the working directory, drop to a non-root user, and point the entrypoint at the bundle's main file. No workspace files or build caches belong here.

Native modules must match production

Packages with compiled addons build against the OS and C library they are installed on. A binary built on glibc will not load on musl-based Alpine, and the reverse is also true. Run the install stage on the same base image family, architecture, and libc as the runtime stage. Never copy node_modules from a developer machine or from the builder stage.

Image builds need registry access

The install stage fetches packages at build time, so the build environment needs outbound network access to your registry. For private registries, pass credentials as a BuildKit secret mount rather than a build argument or environment variable, because those can persist in image layers or history. Never copy .npmrc into the runtime stage.

FROM node:20-bookworm-slim AS builder
WORKDIR /workspace
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
COPY . .
RUN npx nx build api --configuration=production

FROM node:20-bookworm-slim AS install
WORKDIR /app
COPY --from=builder /workspace/dist/apps/api/ ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    npm ci --omit=dev

FROM node:20-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=install --chown=node:node /app/ ./
USER node
CMD ["node", "main.js"]

A three-stage Dockerfile that builds with Nx in a throwaway workspace stage, installs only production dependencies from the generated package.json and pruned lockfile on the same glibc base as runtime, and passes private registry credentials via a BuildKit secret mount.

How do you verify the pruned lockfile and manifest in CI?

Verification has to happen in the pipeline, because a pruning mistake looks fine until the process tries to require a package that never got installed.

Review the manifest like source

Commit a snapshot of each app's generated package.json or print its diff as a CI artifact. When a pull request adds a dependency, reviewers can then see whether the dependency landed in the right app's manifest. A new entry that nobody expected usually points to an import pulled in through a shared library.

Install frozen, then start the app

In the build output directory, run a frozen install against the pruned lockfile: npm ci, pnpm install --frozen-lockfile, or yarn install --immutable. These commands fail if the manifest and lockfile disagree, and that disagreement is the clearest sign that pruning went wrong. Next, start the built image in a clean container with no workspace mounted. Wait for the health endpoint or a startup log line, and fail the job if the process exits. Missing runtime dependencies and dynamically required packages show up here, before production.

Make the cache aware of dependencies

The generated manifest is cached build output. If the build target's inputs leave out {workspaceRoot}/package.json and the root lockfile, Nx can replay a manifest from before a version bump. That stale file will either break the frozen install or quietly install outdated versions. Add both files to the build target's inputs through namedInputs or targetDefaults. For affected detection, let Nx map root package.json changes to the projects that use the changed packages, rather than marking every project affected. Treat lockfile-only changes as a reason to rebuild and smoke-test every deployable app, because transitive resolutions can change under any of them.

#!/usr/bin/env bash
set -euo pipefail
APP=api
OUT=dist/apps/$APP

npx nx affected -t build --base=origin/main --head=HEAD

diff -u "deploy/snapshots/$APP.package.json" "$OUT/package.json"

scratch=$(mktemp -d)
cp "$OUT/package.json" "$OUT/package-lock.json" "$scratch/"
(cd "$scratch" && npm ci --omit=dev --ignore-scripts)

docker build -t "$APP-smoke:ci" -f "apps/$APP/Dockerfile" "$OUT"
docker run -d --name "$APP-smoke" -p 3000:3000 "$APP-smoke:ci"
trap 'docker logs "$APP-smoke" || true; docker rm -f "$APP-smoke" >/dev/null || true' EXIT

for _ in $(seq 1 30); do
  # A missing runtime dependency usually crashes the process at startup.
  if [ "$(docker inspect -f '{{.State.Running}}' "$APP-smoke")" != "true" ]; then
    echo "container exited during startup" >&2; exit 1
  fi
  if curl -fsS  >/dev/null; then
    echo "smoke test passed"; exit 0
  fi
  sleep 2
done
echo "health check timed out" >&2; exit 1

A CI script that builds affected apps, diffs the generated package.json against a committed snapshot, runs a frozen npm ci against the pruned lockfile, and smoke-starts the built image so a missing runtime dependency fails the pipeline.

When is generatePackageJson worth it, and what are the alternatives?

The cost and the payoff

Illustrative estimate, with assumed inputs. The root manifest declares 150 runtime packages, and the app imports 20. Install size and time scale with the resolved transitive tree, not with the number of direct dependencies, and shared transitives overlap. Assume the 20 direct dependencies resolve to about 30% of the full tree. If a full install is 400 MB and takes 90 seconds, the pruned install would be roughly 120 MB and 30 seconds. One heavy native dependency can change this ratio sharply, so measure your own tree.

How generatePackageJson saves engineering time

The larger saving is engineering time, and it comes from work that no longer has to happen:

  • Decoupled deploys. A version bump used only by another app does not change this app's lockfile, so the app does not need a rebuild, a redeploy or a fresh round of testing. Release owners spend less time coordinating changes across services that share nothing but the repository.
  • Smaller CVE triage scope. An advisory against a package outside the pruned lockfile is provably irrelevant to that image. Instead of investigating whether a service loads a flagged package, an engineer can check that service's lockfile and close the finding or route it to the apps that actually ship it.
  • Fewer reinstalls. Docker layer caches stay valid longer, because the install layer's inputs (the pruned manifest and lockfile) change only when this app's dependencies change. Engineers spend less time waiting on image builds in CI and locally.
  • No hand-maintained per-app manifests. Inference through the project graph, including transitive edges through workspace libraries, replaces the manual work of listing each service's dependencies and keeping their versions aligned with the root. Only the analyzer-invisible extras need hand maintenance.
  • Earlier, clearer failures. A frozen install against the pruned lockfile fails in CI when the manifest and lockfile disagree. That is cheaper to diagnose than a version drift discovered in production.
  • Reviewable dependency changes. Per-app manifest snapshots show reviewers which services a new dependency reaches, so questions about blast radius are answered in the pull request rather than after deploy.

The cost is pipeline complexity. Inference gaps, generated artifacts and the verification steps from earlier sections all need ownership. The time saved is real only if that ownership exists. Otherwise the saving moves into debugging missing modules after deploy.

Avoid generatePackageJson when an app already uses most root dependencies, because the pruned subset would be nearly the full manifest. Also avoid it when the team cannot maintain smoke tests. Without them, a missed dynamic require only surfaces in production.

Approach Reproducibility Image size Build-time network Maintenance
Copy root manifest and lockfile High Largest Required Low
Bundle everything High, if externals are handled Smallest None at runtime install Medium (native modules, dynamic imports)
Copy pre-installed node_modules Fragile across OS/arch Large None Low, but risky
Package manager workspace deploy/prune High Small Usually required Low to medium
generatePackageJson + pruned lockfile High Small Required Medium

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx generatePackageJson, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.