How do Nx and Turborepo build the project graph and task graph?
Turborepo is a task runner and cache for JavaScript/TypeScript workspaces. It does not discover projects itself. It reads the package manager's workspace (npm, pnpm, Yarn, or Bun), builds a package graph from the dependencies in each package.json, and then applies the task definitions in turbo.json. Nx also starts from package.json and per-project configuration. Its plugins go further: they infer projects and targets from tool config files, and they add dependency edges by analyzing source imports. In Nx, an import from libs/db creates an edge even when nobody declared it in package.json. In Turborepo, that same edge exists only if it is declared.
Both tools work with two separate graphs:
- The project graph records which code depends on which code.
- The task graph records which tasks must run before which other tasks.
The dependsOn setting connects the two. A caret prefix (^build) means "run build in my dependencies first." A bare name (lint) means "run that task in this same project first."
| Task | Turborepo (turbo.json) |
Nx (nx.json targetDefaults) |
|---|---|---|
| build | "build": { "dependsOn": ["^build"] } |
"build": { "dependsOn": ["^build"] } |
| test | "test": {} |
"test": {} |
Here is how each task fans out for an api service that depends on two shared libraries:
project graph: api ──► shared-db ──► shared-config
api ──► shared-logging
build api: build shared-config ─► build shared-db ─┐
build shared-logging ───────────────────┴─► build api
test api: test api (runs alone)
build api must wait for the shared libraries to compile, because the service bundles their compiled output. test api has no ^ dependency, so it starts immediately. This works when the test runner compiles the libraries' TypeScript source directly. If your tests import built artifacts instead, add ^build to test. Leaving it out lets tests run against stale output.
# Same rules for the api service in both tools.
# build: '^build' runs build in every dependency first.
# test: no dependsOn, so it runs only in the target project.
# Turborepo 2.x: tasks live under "tasks" (1.x called this "pipeline")
cat > turbo.json <<'EOF'
{
"tasks": {
"build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },
"test": {}
}
}
EOF
# Nx: the same rules as targetDefaults, applied to every project
cat > nx.json <<'EOF'
{
"targetDefaults": {
"build": { "dependsOn": ["^build"], "outputs": ["{projectRoot}/dist"], "cache": true },
"test": { "cache": true }
}
}
EOF
# Build api: shared-config, shared-db and shared-logging build first
turbo run build --filter=api
nx run api:build
# Test api: only api's test task runs
turbo run test --filter=api
nx run api:test
# Print the planned tasks without running them
turbo run build --filter=api --dry
# Open the Nx project graph to check edges inferred from imports
nx graph
The same build and test rules written as turbo.json tasks and as nx.json targetDefaults, plus the commands that make 'build api' build the shared libraries first while 'test api' runs only in api.
What goes into the cache key, and how do you declare inputs and outputs?
Both tools compute a hash before running a task and use it as the cache key. The hash covers the task's source files, the hashes of the tasks it depends on, the relevant configuration, and any environment variables you list. On a hit, neither tool runs the command. Each one restores the stored output files and replays the captured terminal log, so CI output looks the same as on a real run. A wrong key causes one of two problems. It can serve a stale artifact. It can also miss every time, and then the cache adds overhead and saves nothing.
| Concern | Turborepo | Nx |
|---|---|---|
| Where declared | turbo.json task entries |
nx.json targetDefaults, namedInputs, project-level targets |
| Inputs | inputs globs. Defaults to the package's git-tracked files |
inputs with named sets such as production and ^production |
| Outputs | outputs globs. Undeclared outputs are not restored |
outputs paths using tokens like {projectRoot} |
| Env vars | env list per task |
{ "env": "NAME" } entries inside inputs |
| Inspecting the hash | --dry or --summarize |
nx show project <name> for resolved config |
Turborepo is explicit. It knows only what turbo.json says. If you forget an outputs glob, the task reports a cache hit but restores no dist folder. Config gets verbose, but every input is visible in one file.
Nx plugins can infer targets, inputs and outputs from the underlying tool's config files. This means less manual work. The cost is an extra layer to debug. If inference guesses wrong, or if a plugin has not caught up with a new config option in the tool it wraps, the effective cache key differs from what you assumed. The first step is to inspect the resolved target before you blame the cache.
// turbo.json: Turborepo hashes only what is listed here
{
"tasks": {
"build": {
"dependsOn": ["^build"], // dependency build hashes feed this key
"inputs": ["src/**", "tsconfig.json", "package.json"],
"outputs": ["dist/**"], // omit this and a hit restores no dist/
"env": ["NODE_ENV", "API_BASE_URL"] // changing these values changes the key
}
}
}
// nx.json: named input sets reused across targets
{
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": ["default", "!{projectRoot}/**/*.spec.ts"] // tests do not bust build cache
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production", { "env": "NODE_ENV" }],
"outputs": ["{projectRoot}/dist"],
"cache": true
}
}
}
# Check what each tool actually resolved before blaming the cache
turbo run build --dry=json # per-task hash, inputs, outputs, env
nx show project orders-api --json # effective targets, including plugin-inferred ones
Equivalent explicit build inputs, outputs and environment variables in turbo.json and nx.json, plus the commands that show the configuration each tool resolved.
Why do environment variables cause incorrect cache hits in backend builds?
Neither tool knows that your build reads DATABASE_URL unless you tell it. If a service bakes a connection string, a feature flag default, or an API key into its bundle at build time, changing that variable leaves the cache key untouched. The next run restores an artifact built against the old value. The task reports success, and the deployed service points at the wrong database or ships with a flag you thought you had turned off.
Declaring env inputs
In Turborepo, list the variables a task depends on in that task's env array in turbo.json. Use globalEnv for variables that should invalidate every task. In Nx, add { "env": "VAR_NAME" } entries to the target's inputs or to a named input shared across projects. Both tools then hash the variable's value into the key. A secret listed this way is not stored in the cache, but its value now determines which artifact gets reused.
The better fix is to keep config out of the artifact entirely. Read database URLs, flags, and secrets at process start from the environment or a secrets manager. The same build output can then serve staging and production, cache hits stay valid, and no credential sits inside a cached tarball.
Tasks that should not be cached
Some tasks are non-deterministic, and caching them produces false greens:
- Integration tests against live databases. The result depends on schema and data state, which neither tool hashes.
- Builds that embed timestamps or build IDs. A cache hit serves a stale value.
- Codegen from remote schemas. The upstream contract can change without any local file changing.
Set cache: false on these tasks in Turborepo, or mark the equivalent targets non-cacheable in Nx.
{
"$schema": "",
// Changes to these invalidate every task's hash in the repo.
"globalEnv": ["NODE_ENV"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"],
// Only vars the bundler actually inlines belong here.
// DATABASE_URL and secrets are deliberately absent: the service
// reads them at process start, so one artifact serves every env.
"env": ["FEATURE_FLAG_DEFAULTS"]
},
"test": {
"dependsOn": ["build"],
"outputs": []
},
"test:integration": {
// Result depends on live DB schema and data, which are not hashed.
"cache": false
},
"codegen": {
// Pulls a remote schema; upstream can change with no local diff.
"cache": false
}
}
}
A Turborepo turbo.json that hashes only the env vars a build really inlines, leaves runtime config such as DATABASE_URL out of the build, and turns off caching for live-database integration tests and remote-schema codegen.
How does remote caching work, and who should be allowed to write to it?
Both tools hash a task's inputs, and on a miss they run the task and upload an archive of the declared outputs plus the captured terminal log under that hash. On a later hit, from any machine, they download the archive, restore the files and replay the log. This is how a developer's laptop and CI runners share one cache: if the hash matches, the work is treated as done, no matter who did it.
Trust model
That last point makes cache writes a supply-chain concern. A cache entry is an unsigned assertion that "these inputs produced these bytes." Anyone with write access can upload a tampered dist/ under a legitimate hash, and every consumer, including the pipeline that builds production images, will restore it without rebuilding. Laptops have uncommitted changes, local toolchains and a much larger attack surface than ephemeral CI runners. Give write tokens only to CI jobs on protected branches, and give developers read-only tokens. Developers still get most of the speed-up, because CI populates the cache for everything that has been merged.
Hosted cache offerings and their pricing change often, so they are not compared here. Check current documentation and weigh self-hosting (you run the storage and access control) against a managed service.
Illustrative estimate (assumed inputs, not measured)
Assume 12 services and 30 libraries, with build and test tasks for each (84 tasks). Each task takes 1 minute, a cache restore takes 5 seconds, and the hit rate is 80%.
| Tasks executed | Task-minutes per run | |
|---|---|---|
| No remote cache | 84 | 84 |
| Remote cache, 80% hits | ~17 + 67 restores | ~22.6 |
At an assumed 40 pipeline runs a day, the difference is about 41 runner-hours daily. That saving shows up directly in CI billing and in shorter feedback loops for engineers.
How do you run only affected services in CI and build small Docker images?
Both tools derive "what changed" by diffing the working tree against a Git ref and walking the graph outward to dependents. In Nx that is nx affected -t build --base=origin/main --head=HEAD. In Turborepo it is a filter such as turbo run build --filter=...[origin/main], where the leading ... also selects packages that depend on the changed ones.
What breaks affected detection
The diff only works if Git has the history to compute it, and neither failure is loud:
- Shallow clones. Many CI checkouts fetch only one commit by default. With a shallow clone, the base commit or the merge base may be missing, so the tool either errors or compares against the wrong point. Fetch enough history to reach the merge base.
- Wrong base ref. Diffing against
HEAD~1on a multi-commit branch silently drops earlier changes.
The diff also only sees files the graph knows about. A Terraform module, a migrations directory or a shared .env.ci that no project claims will change without triggering anything. Model these files as inputs:
- Nx: use
namedInputsorimplicitDependencies. - Turborepo: use
globalDependenciesor per-taskinputs.
Producing small images
turbo prune <service> --docker writes a pruned workspace containing only the target and its internal dependencies. It splits the output into a json folder of manifests and lockfile and a full folder of source. You copy the manifests first and install dependencies in their own layer. Docker can then reuse that cached layer until dependencies actually change.
Nx has no single equivalent. Teams commonly use one of two approaches:
- Have the build executor generate a trimmed
package.jsonfor the compiled output. - Bundle each service into one artifact, then copy only that artifact into a minimal runtime image.
# Build context is the monorepo root; "api" is the workspace package name.
FROM node:20-alpine AS base
# Stage 1: prune the monorepo down to the api service and its internal deps
FROM base AS pruner
WORKDIR /app
RUN npm install -g turbo
COPY . .
RUN turbo prune api --docker
# Stage 2: install deps from manifests only, so this layer stays cached
FROM base AS builder
WORKDIR /app
# out/json holds only package.json files; the pruned lockfile sits in out/
COPY --from=pruner /app/out/json/ .
COPY --from=pruner /app/out/package-lock.json ./package-lock.json
# Re-runs only when a manifest or the lockfile changes, not on source edits
RUN npm ci
# Source changes invalidate the build cache from here down
COPY --from=pruner /app/out/full/ .
RUN npx turbo run build --filter=api
# Stage 3: runtime image without the turbo CLI or unrelated workspaces
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -S app && adduser -S app -G app
USER app
# Copies the pruned workspace with its installed deps. Add a
# production-only install or bundle the service to shrink it further.
COPY --from=builder --chown=app:app /app .
CMD ["node", "apps/api/dist/main.js"]
A multi-stage Dockerfile that runs turbo prune api --docker and copies only manifests and the lockfile before npm ci, so Docker reuses the dependency layer until dependencies change.
What are the alternatives for Go, Python and JVM backends?
Both tools are centered on the JS/TS ecosystem. They can orchestrate other languages, but they model them less precisely.
Nx can treat any directory as a project through a project configuration file and run arbitrary commands as targets. Its plugin API can infer projects and dependency edges from non-JS manifests such as go.mod or a Gradle build. Community plugins exist for several languages, but their maturity varies, so check one before you depend on it.
Turborepo runs any command, but its workspace model is built on package.json. A Go or Python service needs a wrapper package.json whose scripts call go build or pytest. Turborepo does not read go.mod or pyproject.toml, so dependencies between services are invisible to it unless you repeat them as workspace dependencies. Those duplicated declarations drift over time.
| Concern | Nx | Turborepo |
|---|---|---|
| Non-JS projects | Project config or plugin inference | Wrapper package.json per service |
| Cross-language dependencies | Inferred by plugins or declared explicitly | Mirrored manually in package.json |
| Migration cost | Higher: generators, executors, project conventions | Lower: mostly pipeline config |
If your backends are mostly Go, JVM or Python, a language-native build system may fit better. Options include Go's built-in build and test cache, Gradle or Maven for the JVM, or Bazel for hermetic polyglot builds. These tools understand the language's real dependency graph.
Lock-in is uneven between the two. Switching tools in either direction means rewriting pipeline definitions and CI configuration. Nx creates more coupling, because generators, custom executors and its project conventions shape your repository layout. Turborepo's thin config is cheaper to remove.
Should your team choose Nx or Turborepo? A decision checklist
The real question is whether your team wants to own its build structure or delegate it. Turborepo is easy to adopt, but it only knows what you declare: every input, output and environment variable is your responsibility, and every omission becomes a stale cache hit you debug later. Nx gives you structure and boundary enforcement, but you take on its abstractions, and someone has to understand them when they break.
| Criterion | Lean Turborepo | Lean Nx | Avoid both |
|---|---|---|---|
| Team size | A few engineers who review each other's config | Several teams sharing libraries | One or two services, rarely changed together |
| Language mix | Mostly JS/TS, a few package scripts | JS/TS core plus plugins you will maintain | Mostly Go, Python or JVM with native build tools |
| Generators and boundaries | You prefer minimal config | You want scaffolding and enforced module rules | Not relevant |
| Existing CI caching | Weak, and you want quick wins | Weak, and you need affected detection across many projects | Already fast with per-language caches |
- Choose Turborepo if setup cost has to stay low and you can afford review discipline. You save engineering time on day one and pay it back gradually by auditing declared inputs.
- Choose Nx if accidental cross-service imports already cost you incidents or review cycles. Boundary rules turn those into lint failures, which pays off once several teams touch shared code.
- Choose neither if your CI is fast enough today. A monorepo tool adds a dependency to maintain without buying back time.
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 vs turborepo backend, 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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.