How does nx affected -t e2e decide which API e2e tests run?
nx affected answers one question: given the files that changed between two commits, which projects could behave differently? It works in three steps.
- Diff. Nx compares a base commit, usually the merge base with your main branch, against a head commit and collects the changed file paths.
- Map files to projects. Each path is attributed to the project whose root contains it. A file under
libs/shared/money/belongs toshared-money. Some workspace-level files, such as the root lockfile or Nx configuration, can mark many or all projects as touched, depending on how inputs are configured. - Walk dependents. Starting from the directly touched projects, Nx follows the project graph in reverse and marks every project that depends on them, directly or transitively.
With -t e2e, Nx then runs the e2e target on each affected project that defines one. An e2e project runs only if it, or something it depends on, is in the affected set:
libs/shared/money/src/round.tschanged- →
shared-money: affected because it owns the file- →
orders-api: affected because it importsshared-money- →
orders-api-e2e: affected because it depends onorders-api, so it runs
- →
- →
- →
payments-apidepends onshared-auth, notshared-money: not reached- →
payments-api-e2e: skipped
- →
This walk depends on the graph being correct. Nx does not run code or inspect network calls, so it only knows about dependency edges that exist in the graph. If orders-api-e2e only sends HTTP requests to a running orders-api and never imports from it, the edge may not exist, and the walk stops before reaching the e2e project. That gap is the subject of the next section.
# Compare the merge base with main against the current commit.
# Assume only libs/shared/money/src/round.ts changed on this branch.
# List the affected projects without running anything.
npx nx show projects --affected --base=origin/main --head=HEAD
# Illustrative output for the assumed change (order may vary):
# shared-money
# orders-api
# orders-api-e2e
# Run the e2e target only on affected projects that define one.
npx nx affected -t e2e --base=origin/main --head=HEAD
# How the walk reaches each project:
#
# libs/shared/money/src/round.ts (changed file)
# |
# v owned by
# +----------------+
# | shared-money | affected (touched)
# +----------------+
# |
# v imported by
# +----------------+
# | orders-api | affected (dependent)
# +----------------+
# |
# v depended on by
# +----------------+
# | orders-api-e2e | affected -> e2e RUNS
# +----------------+
#
# +----------------+ +----------------+ +------------------+
# | shared-auth | --> | payments-api | --> | payments-api-e2e |
# +----------------+ +----------------+ +------------------+
# not touched not reached e2e SKIPPED
The commands preview and run affected e2e targets between origin/main and HEAD. The diagram shows a change in shared-money reaching orders-api-e2e through the project graph, while the payments-api chain is never reached and its e2e tests are skipped.
Why do API e2e projects miss dependency edges in the Nx graph?
Nx builds most of its project graph by reading source code. It follows import statements and declared package dependencies, and each one it resolves becomes an edge from the importing project to the imported one. An API e2e suite usually has nothing for that analysis to find. It starts the service, or targets one that is already running, and talks to it through HTTP clients, URLs, and JSON fixtures. A route string like /orders/123 is not a module reference, so the e2e project sits in the graph with no edge to the service it exists to test.
This produces a false negative. Suppose someone changes a validation rule in orders-api. nx affected -t e2e reports success and skips the one suite that would have caught the regression. CI shows green because the suite never ran. The failure appears later, on a full run or in a deployed environment, and by then it is harder to connect to the change that caused it. Some generators declare this dependency when they scaffold an e2e project. Hand-written suites and suites migrated from another repo often do not.
The layout that makes this manageable is one e2e project per service: orders-api paired with orders-api-e2e, billing-api with billing-api-e2e. Each e2e project then needs exactly one declared dependency, so the affected set grows only by the suites that match the changed services. A failure in orders-api-e2e points to one service. A shared api-e2e project would depend on every service, run on every change, and give you a failure you still have to trace back to a cause.
How do you model e2e dependencies with implicitDependencies and named inputs?
Start with the edge Nx cannot infer. In apps/orders-api-e2e/project.json, set implicitDependencies to ["orders-api"]. The test project has no imports from the service it exercises, so without this line a change to orders-api never selects its e2e suite.
Cross-service calls need a judgment call. If orders-api calls payments-api over HTTP and the e2e environment runs a real payments container, a payments change can break order flows, so add payments-api as an edge. If the suite stubs payments, leave it out. Shared contract or client libraries need no manual edge. When both services import libs/payments-client, ordinary imports already link them in the graph.
Named inputs work differently. They control the cache hash, not affected selection. Define an e2e named input in nx.json that includes {projectRoot}/Dockerfile, migration directories, .env.template, and OpenAPI specs, and add ^production to pick up dependency sources. Exclude {projectRoot}/**/*.md and !{projectRoot}/**/*.spec.ts. A README edit then makes orders-api affected, but its e2e target is a cache hit instead of a full container run.
Decide on root files yourself rather than accept the defaults. Move shared docker-compose files into an e2e-infra project and add it as an implicit dependency. Treat lockfiles and CI workflow changes as reasons for a full run, handled by a CI path filter.
Both mechanisms have costs. Hand-written edges drift as call graphs change, so review them during service changes. Inputs that are too broad make every target miss the cache, and you are back to paying for the full suite.
// nx.json: reusable input set for anything that changes a running container
{
"namedInputs": {
"e2e": [
"{projectRoot}/src/**/*",
"{projectRoot}/Dockerfile",
"{projectRoot}/migrations/**/*",
"{projectRoot}/.env.template",
"{projectRoot}/openapi/**/*.yaml",
"!{projectRoot}/**/*.md",
"!{projectRoot}/**/*.spec.ts",
"^production"
]
}
}
// apps/orders-api-e2e/project.json
{
"name": "orders-api-e2e",
// orders-api: no imports exist, so Nx cannot infer this edge
// payments-api: listed only because the suite runs a real payments container
// e2e-infra: owns the shared docker-compose files
"implicitDependencies": ["orders-api", "payments-api", "e2e-infra"],
"targets": {
"e2e": {
"executor": "nx:run-commands",
"options": { "command": "jest --config apps/orders-api-e2e/jest.config.ts" },
"cache": true,
// ^e2e resolves the e2e input against each dependency's root,
// so a README edit in orders-api stays a cache hit
"inputs": ["default", "^e2e"]
}
}
}
An e2e named input in nx.json hashes Dockerfiles, migrations, env templates and OpenAPI specs while excluding docs and unit tests, and orders-api-e2e declares its implicit dependencies. Nx accepts comments in these files.
How do you wire e2e targets and isolated environments so parallel runs don't collide?
Once the graph knows which e2e projects to run, the next problem is making sure each one tests the code from the current commit. Put this in targetDefaults so every e2e target inherits it. Set dependsOn to ^build so Nx builds every upstream project, including those added through implicitDependencies, before any test starts. If the e2e project starts the service itself, through a global setup script or a serve step, point that step at the freshly built output rather than at a long-running dev server. A dev server started earlier in the job may still be serving the previous commit's code, and your tests will pass against code you didn't change.
Parallelism is where affected runs break. When --parallel runs three API e2e projects at once, they compete for the same port, database, and container names unless you separate them. Derive each of these from the project name or a job identifier:
- a port offset per project
- a database or schema name suffixed with the project and CI job ID
- a compose project name that namespaces containers and networks
Tests should read these values from environment variables, never from hard-coded defaults.
Caching e2e results needs care. A cache hit replays a pass recorded against a database, queue, or third-party sandbox whose state Nx never saw. If a test touches anything outside the declared inputs, set cache: false on that target. Cache only suites that run fully hermetically, and give them inputs scoped to built artifacts, fixtures, and environment configuration.
{
"namedInputs": {
"e2eFixtures": ["{projectRoot}/fixtures/**/*", "{projectRoot}/jest.config.ts"]
},
"targetDefaults": {
"e2e": {
"dependsOn": ["^build"],
"cache": false
},
"e2e-hermetic": {
"dependsOn": ["^build"],
"cache": true,
"inputs": [
{ "dependentTasksOutputFiles": "**/*", "transitive": true },
"e2eFixtures",
{ "env": "E2E_PROFILE" }
]
}
}
}
An nx.json targetDefaults block that builds upstream projects before every e2e run. Stateful e2e is uncached, and hermetic suites are cached on built outputs, fixtures, and one env variable.
How should CI set base and head for nx affected e2e?
On pull requests, set the base to the merge-base of the PR branch and the target branch, not the target branch's tip. Run git merge-base origin/main HEAD, then pass the result as --base and HEAD as --head to nx affected -t e2e. Diffing against the tip would pull in commits that landed on main after the branch was cut and run e2e suites for services the PR never touched.
On main, use the last commit whose pipeline passed. HEAD~1 only covers the newest commit. If two merges land quickly, or a run fails and the next one succeeds, changes from the skipped commit never get e2e coverage. Store the last green SHA, or query your CI system for it, and diff from there.
| Context | Base | Head | Failure if wrong |
|---|---|---|---|
| Pull request | merge-base with target branch | HEAD |
Tip of target branch adds unrelated projects |
main |
last successful pipeline commit | HEAD |
HEAD~1 skips commits from failed or batched runs |
Shallow clones break both setups. If the base commit isn't in the clone, git can't resolve it. Depending on how your script handles that, the job either fails or falls back to marking every project affected, which hides the problem behind a slow run. Fetch enough history to reach the base. Full history is the simplest option.
Check the selection before you trust it. Run nx show projects --affected with the same base and head and confirm the API e2e projects you expect appear in the list. Open nx graph --affected to see why each project was included. Do this again every time you add a service, because a missing edge produces no error. Its e2e suite simply never gets selected.
#!/usr/bin/env bash
set -euo pipefail
# Make sure the base commit is reachable. A shallow clone may not contain it.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
git fetch --unshallow origin
fi
git fetch origin main
HEAD_SHA=$(git rev-parse HEAD)
if [ "${PIPELINE_CONTEXT:-}" = "pull_request" ]; then
# PR: diff from where the branch left main, not from main's current tip.
BASE_SHA=$(git merge-base origin/main HEAD)
else
# main: diff from the last commit whose pipeline passed, not HEAD~1.
# LAST_GREEN_SHA is stored by your pipeline or fetched from your CI system's API.
BASE_SHA="${LAST_GREEN_SHA:?LAST_GREEN_SHA must be set on main}"
fi
# Fail loudly instead of silently treating every project as affected.
if ! git cat-file -e "${BASE_SHA}^{commit}" 2>/dev/null; then
echo "Base commit ${BASE_SHA} not found in clone; fetch more history." >&2
exit 1
fi
echo "base=${BASE_SHA} head=${HEAD_SHA}"
# Log the selection so reviewers can confirm the expected API e2e projects appear.
npx nx show projects --affected --base="$BASE_SHA" --head="$HEAD_SHA"
# Save the affected graph as an artifact to see why each project was included.
npx nx graph --affected --base="$BASE_SHA" --head="$HEAD_SHA" --file=affected-graph.html
npx nx affected -t e2e --base="$BASE_SHA" --head="$HEAD_SHA"
A CI script that picks the merge-base on pull requests and the last green SHA on main, refuses to run if the base is missing from a shallow clone, and logs the affected projects and graph before running e2e targets.
When should you avoid affected-only e2e, and what are the alternatives?
Affected-only selection is only as good as the graph, and some coupling never shows up in source imports. A service that publishes to a queue has no edge to the consumer that reads from it. Two services sharing a database schema look independent until a migration in one breaks queries in the other. Feature flags and config fetched at runtime change behaviour without touching any file Nx hashes. If your services talk mostly through these channels, affected-only e2e will often skip the one suite that would have caught the regression, and it will skip it silently.
Size matters too. With two or three services, the full API e2e suite may finish in a few minutes. In that case, maintaining implicitDependencies and named inputs costs more attention than it saves in CI time. Run everything on every PR until the suite gets slow enough to hurt.
For larger repos, combine approaches instead of picking one:
| Approach | Detection speed | CI cost | Maintenance effort | False-negative risk |
|---|---|---|---|---|
| Run everything on every PR | Immediate | High, grows with service count | Low | Lowest |
| Affected-only e2e | Immediate for modelled edges | Low | Medium: graph edges need upkeep | High for runtime coupling |
| Contract tests for shared-library changes | Immediate at the API boundary | Low | Medium to high: contracts must track real usage | Low for interface breaks, none for behaviour |
| Scheduled full runs (nightly) | Delayed by hours | Fixed and predictable | Low | Low, but failures arrive after merge |
A common pairing is affected-only on PRs plus a scheduled full run. The nightly job acts as a safety net for edges the graph cannot see. When it catches something the PR run missed, treat that as a signal to add the missing dependency.
What does a layered e2e strategy cost, and where does it save engineering time?
Make the override explicit. A PR label or a manual workflow input that switches the job from nx affected -t e2e to nx run-many -t e2e lets a reviewer force the full suite when a change touches shared infrastructure the graph may not see, such as a migration, a gateway route, or an auth config. Main or a nightly schedule runs everything unconditionally.
Illustrative estimate (assumed numbers, not a benchmark). Assume 12 API e2e projects, 8 minutes each, 4 parallel CI agents, 40 PR runs per day, and an average of 2 affected e2e projects per run.
- Full suite per PR run: 12 × 8 = 96 agent-minutes, about 24 minutes wall clock.
- Affected per PR run: 2 × 8 = 16 agent-minutes, about 8 minutes wall clock.
- Daily savings = R × (N − A) × T − S × N × T = 40 × 10 × 8 − 1 × 12 × 8 = 3,104 agent-minutes, where R is PR runs, N is total projects, A is affected projects, T is minutes per project and S is scheduled full runs.
Plug in your own R, N, A and T. If A approaches N because most changes touch a shared library, the savings disappear.
The costs are real:
- Config overhead. Someone has to write the implicit dependencies, the named inputs and the environment isolation.
- Edge maintenance. These need updating every time a service gains a new runtime dependency.
- Nightly triage. Failures from the scheduled run belong to no single PR, so assign an owner or they rot.
- Delayed detection. A missed edge surfaces hours later, after other merges have piled on top and bisecting is harder.
The return is faster PR feedback and a sharper signal. A failure in two suites points at the change under review. A failure somewhere in twelve points at whatever broke.
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 affected e2e, 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.