How does Nx decide a cache hit, and where do environment variables fit?
Before running a target, Nx computes a task hash: a fingerprint built only from what the task declares as its inputs. Typical ingredients are:
- Source filesets: the project's files, filtered by named inputs such as
productionordefault. - Dependency inputs: the hashed inputs of projects this one depends on, pulled in with the
^prefix. - Runtime inputs: the output of a command such as
node -v, captured as a string. - Env inputs: the values of specific environment variables you name.
- Task configuration: the target's own options and command.
Nx looks that hash up in the local cache and then, if configured, the remote cache. On a hit, it does not run the task. It restores the stored output files and replays the stored terminal log, so the run looks the same as a real execution.
source files ─┐
dep inputs ───┤
runtime cmds ─┼──► task hash ──► cache lookup ──┬─ hit ──► restore outputs + replay logs
declared env ─┤ (local/remote) └─ miss ─► run task ──► store outputs + logs
target config ┘
undeclared env (API_URL, NODE_ENV, ...) ──X never reaches the hash
The core rule is that an environment variable you didn't declare is invisible to the hash. Suppose API_URL changes from staging to production while the source stays the same. The hash doesn't change, so Nx replays the staging build and reports success. Nothing fails, which is why this kind of bug survives review.
Every environment variable a task reads is therefore a cache-correctness decision. This matters most for backend and platform engineers who run Nx with local or remote caching. Remote caching makes it worse, because one misconfigured CI run can push a stale artifact that every developer and pipeline then reuses.
┌─────────────────────────┐
│ source filesets │──┐
│ dependency inputs (^) │──┤
│ runtime cmd (node -v) │──┤ ┌────────────┐
│ declared env vars │──┼─────►│ task hash │
│ target options/command │──┘ └─────┬──────┘
└─────────────────────────┘ │
┌─────────────────────────┐ ▼
│ undeclared env │ ┌──────────────────┐
│ API_URL, NODE_ENV, ... │──X │ cache lookup │
└─────────────────────────┘ │ local → remote │
(never reaches the hash) └───┬───────────┬──┘
hit │ │ miss
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ restore outputs │ │ run task │
│ replay stored log│ └────────┬─────────┘
│ (task not run) │ │
└──────────────────┘ ▼
┌──────────────────┐
│ store outputs + │
│ log in cache │
└──────────────────┘
Only declared inputs feed the Nx task hash. On a local or remote cache hit, Nx restores stored outputs and replays the stored log without running the task, so a changed undeclared variable such as API_URL yields stale results.
Which environment variables should be Nx inputs?
Classify each variable by one question: does changing its value change the bytes the target writes, or the result it reports? If yes, it belongs in the hash. If no, declaring it only adds cache misses.
| Variable kind | Example | Declare as input? | Why |
|---|---|---|---|
| Build-time, inlined into output | Public API base URL baked into a frontend bundle | Yes | A different value produces a different artifact. Omitting it replays a bundle that points at the wrong environment. |
| Compiled feature flag | Flag that triggers dead-code elimination at build time | Yes | The flag decides which code ships. |
| Runtime-only | Database password used by integration tests or at service startup | Usually no | The artifact is identical whatever the value is. The value only matters when the process runs. |
| Volatile | Build timestamp, commit SHA, per-run IDs | Avoid | It changes on every run, so every run misses the cache. Inject it at deploy time or in an uncached step. |
| Secret | API signing key, rotated token | Never inline into output | An artifact that contains a secret leaks it to anyone who can read the cache. |
The runtime-only row has an exception. If a variable changes what a test exercises, such as which backend it targets, it changes the reported result and should be declared.
Declaring a secret as an input is safe in one narrow sense: Nx hashes the value, so the plaintext does not appear in the cache key. The cost is that cache validity becomes tied to rotation. Every time the credential rotates, every dependent target misses, even though nothing it produces has changed. If a secret seems to need hashing, that usually means it is being compiled into output, which is the real problem to fix.
How do you declare env inputs in nx.json and project targets?
Nx expresses an environment variable dependency as an input object of the form { "env": "VAR_NAME" }. Nx reads the variable's value at hash time and folds it into the task hash. If the variable is unset, Nx still hashes that state, so changing from unset to set also produces a miss.
You can place this object in two locations:
- A target's
inputsarray. The variable then applies only to that target. - A named input. For example, you can define a
buildEnventry undernamedInputsinnx.jsonthat lists{ "env": "API_URL" }and{ "env": "PUBLIC_BASE_PATH" }. You then add"buildEnv"to thebuildinputs undertargetDefaults, next to"default"and"^default", and every project's build picks it up.
Watch the precedence rule. When a project declares its own inputs for a target, that list replaces the default list instead of adding to it. If the project omits "buildEnv", its env dependencies are no longer hashed, and nothing reports the omission.
| Approach | Strength | Cost |
|---|---|---|
Shared buildEnv in targetDefaults |
One list to review in a single PR. Hard to forget a variable. | A change to any listed variable invalidates every build, including projects that never read it. |
Per-target { "env": ... } inputs |
Each project's hash covers only the variables it actually consumes. | Lists spread across many files and drift as code changes, with no central place to audit them. |
A workable default is to put variables that most builds really consume in the shared named input. Declare per-target entries only for variables that one or two projects use, and add a review checklist item that compares those entries against the code that reads them.
// nx.json: shared env inputs, applied to every project's build
{
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"buildEnv": [
{ "env": "API_URL" },
{ "env": "PUBLIC_BASE_PATH" }
]
},
"targetDefaults": {
"build": {
// Most builds read these vars, so hash them centrally
"inputs": ["default", "^default", "buildEnv"]
}
}
}
// apps/admin/project.json: per-target override for a var only this app reads
{
"name": "admin",
"targets": {
"build": {
// This list REPLACES the targetDefaults inputs, so restate
// default, ^default and buildEnv or they stop being hashed
"inputs": [
"default",
"^default",
"buildEnv",
{ "env": "ADMIN_SSO_ISSUER" }
]
}
}
}
A shared buildEnv named input wired into targetDefaults, plus a project-level build override that has to restate the shared inputs because it replaces the default list instead of extending it.
Do .env files affect the Nx cache hash?
Nx reads .env files and injects their values into the environment of the task it runs. Depending on your setup, that can include a workspace-level file, a file in the project root, and variants named after a target or configuration. The exact set of filenames Nx looks for has shifted over time, so check the documentation for the version you run. Loading a file is not the same as hashing it. A value can reach your compiler without ever reaching the cache key.
File-based inputs usually respect .gitignore. A typical .env.local is gitignored, which keeps it out of commits. It also keeps it out of any fileset glob you might write. A developer can change API_BASE_URL in that file, rerun the build, and get a cache hit carrying the old value. Widening the glob does not reliably fix this. What fixes it is declaring the specific variables the build reads as env inputs. Nx then hashes the value the task actually sees, whatever file or shell it came from.
Precedence adds another trap. When a variable is set in both the shell or CI environment and a .env file, which one wins is not something to assume. Test it in your own workspace, and avoid defining the same variable in both places.
Developer-local .env.local is fine for runtime configuration, such as a dev server pointing at a local database. It becomes dangerous when it feeds cacheable build output, such as an inlined public URL or a feature flag. That artifact can be uploaded to a shared cache and replayed on CI or on a teammate's machine.
{
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"default",
"^default",
{ "env": "API_BASE_URL" },
{ "env": "FEATURE_NEW_CHECKOUT" }
]
}
},
"namedInputs": {
"default": ["{projectRoot}/**/*"]
}
}
An nx.json snippet that declares the variables a build inlines as env inputs, so Nx hashes the value the task sees whether it came from a gitignored .env.local or the shell.
How do secrets leak through the remote cache and CI?
A cache entry holds two things: the files a target declared as outputs, and the terminal output the task printed. On a hit, Nx restores both. If a secret ended up in either, anyone who can read the cache gets it back, including people who were never given the secret.
Where secrets end up
The first leak path is bundled output. A bundler that inlines process.env values at build time will write an API key into a JavaScript file in dist just as it writes a public URL. Search your build outputs for known secret values and patterns before trusting them.
The second path is logs. A script that runs echo $DATABASE_URL, or a tool that prints its resolved config in verbose mode, puts the secret into captured terminal output, and that output is replayed on every cache hit. Treat permission to read the cache as read access to every build output and log it contains.
CI practice
- Inject secrets from the CI secret store as process environment variables at runtime. Do not commit
.envfiles, and do not generate them in a step that persists them to disk or into artifacts. - Scope each secret to the jobs that need it. A lint job has no use for deploy credentials.
- Do not let untrusted branches or forks write to a cache that trusted pipelines read. If they can write, they can poison builds that later run with real secrets.
Deleting a cache entry does not undo a leak, because you can't know who has already read it. If a secret has leaked, rotate it.
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
env:
# Only pushes to trusted branches get a read-write cache token.
# PRs, including forks, get a read-only token so they cannot write to the cache.
NX_CLOUD_ACCESS_TOKEN: ${{ github.event_name == 'push' && secrets.NX_CLOUD_RW_TOKEN || secrets.NX_CLOUD_RO_TOKEN }}
steps:
- uses: actions/checkout@v4
- run: npm ci
# This job gets no app secrets, so none can be inlined into dist or printed to logs.
- run: npx nx run-many -t lint test build
# Audit the bundles for secret-shaped strings before they are cached or shipped.
# -l prints only filenames, so a match does not echo the secret into the log.
- run: |
if grep -rlE 'sk_live_[A-Za-z0-9]{16,}' dist/; then
echo "Possible secret inlined in build output" >&2
exit 1
fi
deploy:
needs: build
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
# Secrets are scoped to this one step and exist only as process env.
# Nothing writes them to a .env file on disk or into an artifact.
# --skip-nx-cache keeps deploy output out of the cache entirely.
- run: npx nx run api:deploy --skip-nx-cache
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}
A GitHub Actions workflow that gives only trusted pushes a read-write cache token, keeps app secrets out of the cached build job, checks dist for secret-shaped strings without printing them, and injects deploy secrets as step-scoped env vars.
What does over- or under-declaring cost in engineering time?
Both mistakes cost time; they just bill it differently. Under-declaring makes builds look fast while a cached artifact quietly carries the wrong value, such as a staging API URL inlined into a production bundle. Nothing fails in CI. The cost shows up later as incident triage, plus the time it takes someone to realize the cache served it. Over-declaring is visible and cheap to diagnose, but it erodes the remote cache until it stops paying for itself.
| Under-declaring | Over-declaring | |
|---|---|---|
| Symptom | Wrong config in a "successful" build | Frequent cache misses |
| Detection | Late, often in production | Immediate, in CI duration |
| Cost type | Debugging and incident time | Compute and wait time |
Illustrative estimate (assumed numbers, not a benchmark). Assume one secret is rotated weekly and declared as an input on a build target that 40 projects depend on. Each build takes 3 minutes. Two pipelines (main plus one release branch) run cold before the cache repopulates.
Wasted minutes per week = rotations × affected projects × build minutes × cold pipelines = 1 × 40 × 3 × 2 = 240 CI minutes.
If you declare only non-secret variables that change the output, such as a public API base URL, invalidation happens only when that value actually changes. That might be a few times a year, so the weekly waste is close to zero.
The secret should not be an input at all. If the artifact never contains it, its value cannot change the output, so it should not change the hash. When a variable does belong in the artifact but rotates often, you have three alternatives:
- Read it at runtime instead of inlining it at build time.
- Inject a config file at deploy time, so one artifact serves every environment.
- Disable caching for that specific target, and accept the rebuild cost for that target only.
How do you debug a suspected stale cache hit in Nx?
When a build behaves as if it read yesterday's configuration, treat it as a hashing question first and confirm it with a repeatable procedure rather than clearing the cache and moving on.
- Inspect what Nx thinks the inputs are. Run
nx show project <name>and read the resolved target configuration. It shows the result aftertargetDefaults, named inputs, and plugin-inferred targets are merged. Inputs you defined innx.jsonmay have been overridden at the project level, so check this merged view rather than either file alone. If the variable you suspect isn't listed as anenvinput, Nx has no way to see it. - Change one variable and re-run. Alter only that value and run the same task again. If Nx reports a cache hit, the variable is not part of the hash. If the task re-runs, the input is wired correctly and the stale output came from somewhere else, such as a file outside the declared inputs or a value read at runtime.
- Compare against a fresh execution. Run the task with
--skip-nx-cacheand diff the output against the cached artifact. If they match, the cache wasn't stale and the problem is elsewhere. If they differ, a missing input is the likely cause.
Checklist for adding a new variable
- Does it change build output? Declare it as an
envinput on every target that reads it. - Is it a secret? Keep it out of artifacts, cache entries, and logs, and inject it at runtime instead.
- Is it per-developer and local-only? Put it in a gitignored
.env.localand confirm that no cacheable target's output depends on it.
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 environment variables cache, 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.