What does it mean to add Nx to an existing repo, and who is it for?
Adding Nx to an existing repo means putting a task runner and cache in front of the commands you already have. Nx does not replace your build tool, test framework or package manager. Your build, test and lint scripts keep doing the real work. Nx decides whether each one needs to run, in what order, and whether a previous result can be reused.
Conceptually, nx init adds Nx as a dev dependency and creates an nx.json configuration file. It then treats your existing package.json scripts as Nx targets. You do not have to move services into an apps/ or libs/ folder, and you do not have to rewrite build configs. That matters for incremental adoption: you can run nx run-many across your current layout on day one and restructure later, or never.
The teams that benefit most are backend and platform teams with several services or shared packages in one repository and CI that rebuilds and retests everything on each push. For them, two features pay off:
- Cached results: a target whose inputs haven't changed is restored instead of re-executed.
- Affected-only runs: a change to one package triggers work only in that package and the projects that depend on it.
A single-service repo with a fast pipeline usually gains little from Nx. For that repo, Nx is one more tool to maintain.
Polyglot backends need more manual setup. Nx infers much less about Go, Java or Python projects than about JS/TS projects. Teams usually wrap the existing commands (go test, mvn package, pytest) as targets and declare their inputs and outputs by hand. Without those declarations, caching and affected detection aren't trustworthy.
What should you check before running nx init?
Before nx init touches anything, collect the facts that every later decision depends on.
Inventory the existing entry points. List every build, test and lint command the team actually runs: Makefile targets, shell scripts, package scripts and the steps buried in CI config. For each one, record what it reads and what it writes. Then mark it deterministic or not. Nx can only safely replay tasks whose outputs depend entirely on declared inputs. A test that hits a shared database, or a build that embeds a timestamp, will return stale results from cache.
| Task type | Typically deterministic? | What breaks determinism |
|---|---|---|
| Lint | Yes | Config files outside the project directory |
| Unit tests | Usually | Network calls, unseeded randomness, wall-clock time |
| Integration tests | Rarely | Shared databases, external services |
| Build/package | Often | Embedded timestamps or commit SHAs |
| Code generation | Yes, if the generator version is pinned | Unpinned generator versions |
List environment variables and generated files that affect outputs. Examples include target OS and architecture variables, build profiles, .env files, and generated protobuf or OpenAPI clients. Each of these becomes a declared input later. If one is missing, the cache can serve an artifact built for the wrong configuration.
Record a CI baseline. Take the median wall-clock duration of recent main-branch pipelines, both overall and per job. Without that number, you cannot show whether the adoption helped.
Isolate the change. Run nx init on a dedicated branch and open a PR that contains nothing else. Review every file it creates or modifies, including nx.json, the package manifest and .gitignore entries. If the change needs to be reverted, you can close or revert that one PR.
Pin the Nx version exactly. Use an exact version, not a caret or tilde range, so developers and CI run identical tooling. Upgrades then become deliberate PRs that go through nx migrate.
#!/usr/bin/env bash
# Pre-flight inventory before nx init. Read-only until the final block.
set -euo pipefail
NX_VERSION="${1:?usage: preflight.sh <exact-nx-version>}"
# 1. Inventory entry points: Makefile targets, package scripts, CI steps.
echo '== Makefile targets =='
[ -f Makefile ] && grep -E '^[A-Za-z0-9_.-]+:' Makefile | cut -d: -f1 | sort -u
echo '== package scripts =='
[ -f package.json ] && npm pkg get scripts
echo '== CI run steps =='
grep -rn 'run:' .github/workflows 2>/dev/null || true
# 2. Environment variables referenced by build tooling; each becomes a declared input.
echo '== env vars referenced =='
grep -rhoE '\$\{?[A-Z_][A-Z0-9_]*' Makefile scripts/ 2>/dev/null \
| tr -d '${' | sort -u
# 3. Inputs that are easy to miss: .env files and checked-in generated code.
echo '== .env and generated files =='
git ls-files '*.env' '.env*' '*.proto' '*.pb.go' '*_pb2.py' 'openapi*.y*ml'
# 4. Determinism red flags: timestamps or commit SHAs embedded in builds.
echo '== possible non-determinism =='
grep -rnE 'date \+|git rev-parse|BUILD_TIME|GIT_SHA' Makefile scripts/ 2>/dev/null || true
# 5. Isolate the change: dedicated branch, nothing else in the PR.
git switch -c chore/nx-init
npx nx@"$NX_VERSION" init
# Pin the exact version so every machine and CI runner resolves the same Nx.
npm install --save-dev --save-exact "nx@$NX_VERSION"
# Review every created or modified file (nx.json, package.json, .gitignore).
git status --short
git diff
A read-only inventory of build entry points, environment variables, generated files and determinism risks, followed by running nx init on a dedicated branch with an exactly pinned Nx version and a full diff review.
How does Nx caching work, and which targets should be cacheable?
Before each run, Nx computes a hash from the target's declared inputs: source files, relevant config, selected environment variables, and the hashes of dependency projects. If that hash already exists in the cache, Nx skips execution, replays the stored terminal output, and restores the declared output directories. Nx only knows what you declare, and the cache has no way to detect anything you leave out.
| Target | Cacheable? | Why |
|---|---|---|
build |
Yes | Same inputs produce the same artifacts |
test |
Yes, if hermetic | Only when it uses no live databases, clocks or network |
lint, typecheck |
Yes | Pure functions of source and config |
deploy, migrate, publish |
Never | The side effect is the point. A cache hit would skip the work and still report success |
Caching a non-deterministic task is worse than not caching it. A flaky test that passes once gets frozen as a permanent pass. A build that embeds a timestamp gets served to CI with stale content. Either way, nothing on the screen tells you it happened.
Declaring inputs and outputs
Inputs should cover the project's source, shared config such as the root tsconfig and lockfile, and any environment variables that change behaviour. Outputs should list every directory the target writes, such as dist or coverage.
There are two main failure modes:
- Missing inputs produce stale hits. You change a config file, and Nx returns the old result.
- Missing outputs produce runs that report "successful" but restore no artifacts. Downstream steps then fail, or quietly use leftover files.
Verify before enabling
Work through one target at a time:
- Run the target twice and confirm the second run is a cache hit.
- Edit one declared input, such as a source file, config file or environment variable, and confirm the next run is a miss.
- Delete the output directory, rerun the target, and confirm the artifacts are restored.
Only mark a target cacheable after all three checks pass.
{
"namedInputs": {
"sharedGlobals": [
"{workspaceRoot}/tsconfig.base.json",
"{workspaceRoot}/package-lock.json",
{ "env": "NODE_ENV" }
],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": ["default", "!{projectRoot}/**/*.spec.ts"]
},
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"outputs": ["{projectRoot}/dist"]
},
"test": {
"cache": true,
"inputs": ["default", "^production"],
"outputs": ["{projectRoot}/coverage"]
},
"lint": {
"cache": true,
"inputs": ["default", "{workspaceRoot}/.eslintrc.json"]
},
"deploy": { "cache": false },
"migrate": { "cache": false }
}
}
An nx.json that caches build, test and lint with explicit inputs (source, root config, lockfile, NODE_ENV) and output directories, while keeping deploy and migrate uncached.
How do task dependencies and the project graph drive affected CI?
Start with targetDefaults in nx.json. Setting dependsOn: ["^build"] on the build target tells Nx that a project's build must wait for the builds of the projects it depends on. Without it, Nx may run a service build before the shared library it imports has been compiled.
Nx infers the project graph from source: it reads package.json dependencies and parses imports. Run nx graph and check the edges against what you know about the system. A missing edge means affected will skip a project that changed behavior. An extra edge only costs build time.
Inference misses dependencies that don't appear as imports:
- Shared config. Root
tsconfig, lint rules, or Docker base files that many services consume. Add them tonamedInputsso a change invalidates the right projects. - Generated code. Clients generated from OpenAPI or protobuf schemas. Declare
implicitDependencieson the schema project. - Scripts that read sibling directories. Migration runners or seeders that use relative paths into another project. Declare these edges explicitly too.
Roll out affected runs in stages. First, run nx affected in CI alongside the existing pipeline without letting it gate merges. Log which projects it selects and compare them with what the full pipeline actually exercised. Switch to affected-only once those two sets agree consistently.
Affected detection depends on the diff. Set --base to the merge base with your main branch, not the previous commit. Fetch enough git history for that merge base to exist, because shallow clones break the comparison. Keep a scheduled full run on main as a safety net for any edges the graph still misses.
#!/usr/bin/env bash
# Stage 1 of the rollout: run Nx affected in shadow mode next to the existing pipeline.
set -euo pipefail
# Affected detection diffs against the merge base. CI checkouts are often
# shallow, so the merge base may be missing. Fetch full history if needed.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
git fetch --unshallow --no-tags origin
fi
# Make sure origin/main exists locally. Some CI checkouts fetch only the PR ref.
git fetch --no-tags origin main
# Compare against where this branch forked from main, not against HEAD~1.
BASE="$(git merge-base origin/main HEAD)"
HEAD_SHA="$(git rev-parse HEAD)"
echo "Affected base: $BASE head: $HEAD_SHA"
# Record which projects Nx selects. Keep this file as a CI artifact and compare
# it with what the full pipeline actually built and tested.
npx nx show projects --affected --base="$BASE" --head="$HEAD_SHA" \
| sort > nx-affected-projects.txt
cat nx-affected-projects.txt
# Shadow mode (default): run affected targets but never fail the job,
# so the existing pipeline stays the merge gate.
# Set NX_GATING=true only after the two sets agree consistently.
if [ "${NX_GATING:-false}" = "true" ]; then
npx nx affected -t build test --base="$BASE" --head="$HEAD_SHA"
else
npx nx affected -t build test --base="$BASE" --head="$HEAD_SHA" \
|| echo "nx affected failed (shadow mode, not gating)"
fi
# Separately, schedule a full run on main (for example nightly) as a
# safety net for edges the project graph still misses:
# npx nx run-many -t build test
A CI script that computes the merge base with main, avoids shallow-clone failures, logs the projects Nx marks as affected for comparison, and runs affected targets without gating merges until you turn gating on.
When should you enable remote caching, and when should you avoid Nx entirely?
Local caching only helps the machine that produced the artifact. A remote cache shares outputs across CI runners and developer laptops. A test suite one runner has already executed for a given set of inputs becomes a download for every other runner. This is worth having, but it is a separate decision from adopting Nx, and it carries its own risks.
Questions to answer before enabling a remote cache
- Who can write to it? Restrict writes to CI jobs running on trusted branches. If any laptop or fork-triggered pipeline can upload, any of them can publish an artifact that others will trust.
- What is the poisoning risk? A cache hit replays stored outputs without re-running the task. If an entry was produced from undeclared inputs, such as an environment variable or a tool version outside the hash, every consumer receives the wrong result and nothing fails. A misconfigured cache spreads bad artifacts faster than a misconfigured build.
- What happens when it is unavailable? The cache becomes an external dependency of CI. Confirm that builds fall back to local execution and decide who owns the credentials, retention policy and cleanup.
When to avoid or delay Nx
- Single-service repos. With one deployable and one test suite, the project graph has nothing to prune, and the configuration costs more than it saves.
- Teams that won't run tasks through Nx locally. If engineers keep calling the underlying tools directly, local caching is unused and CI behaviour drifts from local behaviour.
- Inputs you can't declare reliably. Builds that depend on network fetches, mutable system state or generated files outside the workspace produce hashes that don't reflect reality. Caching those builds is unsafe.
What are the alternatives, and how does Nx affect engineering cost and time?
The real choice is not "Nx or nothing." It is which layer of tooling you are willing to maintain.
| Option | What you get | Ongoing cost |
|---|---|---|
| Plain scripts + CI-level caching | Dependency and artifact caches keyed on lockfiles | Low. No task graph, so every job runs everything |
| Other monorepo task runners | Similar task caching and graph-based filtering | Similar learning curve and config upkeep |
| Language-native build tools | Fine-grained incremental builds within one ecosystem | Weak across languages; high cost to adopt hermetic tools |
| Do nothing | Nothing new | CI time grows with the repo |
Nx's costs are real. Engineers have to learn targets, inputs and outputs. Configuration drifts as projects change. Nx version migrations can rewrite config across the whole repo, and someone has to review those diffs. Habits also change, such as running tasks through Nx instead of calling tools directly. The return comes from skipped work, and only for projects you have onboarded. If half the repo still runs through untracked scripts, that half gets no caching or affected filtering.
Illustrative estimate (assumed numbers, not a benchmark)
Monthly net hours = (CI minutes saved per run × runs per month ÷ 60) + local hours saved − maintenance hours
Assume these inputs:
- 8 minutes saved per run
- 1,200 runs per month
- 20 local hours saved per month
- 25 hours per month of upkeep
That gives (8 × 1,200 ÷ 60) + 20 − 25 = 155 hours per month. If you halve the saved minutes and double the upkeep, the result is 80 + 20 − 50 = 50 hours per month. That is still positive, but a slow migration could erase it.
Optional later stages, rollback plan and copy-paste checklist
Optional later stages
Each stage below stands alone. Stopping after caching and affected CI, or skipping any of these stages, is a valid outcome.
| Stage | What you gain | Exit cost |
|---|---|---|
| Plugins for inferred targets | Less hand-written target config | High: targets live in plugin logic, not your scripts |
| Module boundary lint via project tags | Enforced dependency rules between layers | Low: delete tags and the lint rule |
| Generators for new services | Consistent scaffolding | Low: generated code stays plain code |
| Monorepo folder layout | Clearer project discovery | Medium: imports and paths change |
Adopt opinionated plugins last. Once a plugin infers your build and test targets, your package scripts stop being the source of truth, and removing Nx means rebuilding that logic yourself.
Rollback plan
As long as every target still calls an existing script, removing Nx means deleting nx.json, any project.json files and the Nx dependencies, then reverting the CI changes so pipelines call the scripts directly. Keep the pre-Nx CI config in version control history so you can restore it quickly.
Checklist
- Baseline: Record current CI duration. Done when the number is written down.
- Init: Run
nx initon a branch. Done when existing scripts run unchanged through Nx. - Caching: Mark deterministic targets cacheable. Done when a second run hits the cache with identical output.
- Affected CI: Switch CI to affected runs. Done when an untouched project is skipped and an edited dependency triggers its dependents.
- Remote cache (optional): Done when CI reuses an artifact built elsewhere.
- Later stages (optional): Done when each one is adopted or explicitly declined.
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 add nx to existing repo, 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.