How does Nx compute a task hash, and why do missing env inputs cause wrong cache hits?
Before Nx runs a cacheable task, it computes a hash from everything the task declares as an input. By default that means the project's source files, the source of the projects it depends on, relevant global configuration, and the task's own command and options. You can add environment variables, extra files, and the output of runtime commands to that list. If a later run produces the same hash, Nx skips execution and restores the stored outputs and terminal log.
The hash is the cache key, and Nx treats it as the whole truth. It never inspects what your build actually reads. If a value changes the output but is not a declared input, Nx cannot know it matters. Two runs that differ only in that value get the same hash. The second run returns the first run's artifacts with no warning, because from Nx's point of view nothing changed.
A concrete failure
Suppose a frontend build inlines API_BASE_URL into its bundle at compile time, and the variable is not listed as an input.
- CI builds for staging with
API_BASE_URLpointing at the staging API. Nx computes hashH, runs the build, and caches the bundle underH. - A production build runs on the same commit with the production URL. The source files, dependencies, and options are unchanged, so the hash is still
H. - Nx reports a cache hit and restores the staging bundle.
- Production ships with the staging URL baked in.
Nothing fails and the logs look normal. The bug only shows up when production traffic starts hitting staging.
This is why handling environment variables in Nx is a question of cache key design, not only a question of where .env files live. Every value that can change a task's output has to be part of the key. Otherwise the cache will eventually return a wrong result that looks like a correct one.
STAGING CI RUN PROD CI RUN
API_BASE_URL=staging API_BASE_URL=prod
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ src, deps, config, │ │ src, deps, config, │
│ command, options │ │ command, options │
│ API_BASE_URL: absent │ │ API_BASE_URL: absent │
└──────────┬───────────┘ └──────────┬───────────┘
▼ ▼
┌───────────┐ ┌───────────┐
│ hash = H │ │ hash = H │
└─────┬─────┘ └─────┬─────┘
│ miss: run build │ hit: skip build
▼ │
┌──────────────────────┐ │
│ bundle, staging URL │ │
│ inlined at compile │ │
└──────────┬───────────┘ │
│ store under H │
▼ ▼
┌──────────────────────────────────────────────────────────┐
│ Nx cache: H ──► staging bundle + terminal log │
└─────────────────────────────┬────────────────────────────┘
│ restore H
▼
┌──────────────────────────────┐
│ prod ships the staging URL │
└──────────────────────────────┘
Because API_BASE_URL is not a declared input, the staging and production builds hash to the same key H, so the production run gets a cache hit and restores the staging bundle without any warning.
How does Nx load .env files, and does loading a variable mean it is hashed?
Nx can load .env files for you before a task runs, which is convenient and also where many wrong cache hits start. The loading model has three layers:
- Workspace-level files at the repository root apply to every project.
- Project-level files in a project's root apply only to that project's tasks.
- Target- or configuration-specific variants are files whose names include the target or configuration, such as a variant for
buildor for aproductionconfiguration. They apply only when that target or configuration runs.
More specific files take precedence over general ones, so a project's production build value overrides a workspace default. Variables already set in the shell or CI environment may also interact with file values. The exact file names, the full precedence order, and how pre-existing environment variables are treated have changed across Nx releases. Check the documentation for the Nx version in your lockfile, and don't rely on older blog posts or answers that describe a different scheme.
Loaded is not the same as hashed
Dotenv loading puts values into the task's process environment. It does not, by itself, add those values to the task hash. These are separate mechanisms. One decides what the running process can see. The other decides what Nx compares when it looks for a cached result.
This leads to a failure that is easy to miss. You change API_BASE_URL in a root .env file. The build embeds the new value, but the hash is unchanged. Nx then replays the old output with the old URL. A project-level .env might be covered by a file-input pattern that happens to match the project's files, but you can't count on that. Treat any loaded variable that affects output as undeclared until you add it to the task's inputs explicitly.
How do you declare env, file and runtime inputs in Nx?
Inputs live in a target's inputs array, either in project.json or in targetDefaults in nx.json. Each entry adds something to the hash.
Environment variables
To hash a single variable, add an object such as {"env": "API_URL"} next to your file inputs: "inputs": ["default", {"env": "API_URL"}]. Nx hashes the variable's value. A different value produces a different hash, so a staging build is never reused for production.
.env files as file inputs
If a .env file's contents should invalidate the cache, add it as a file input, for example "{projectRoot}/.env" or "{workspaceRoot}/.env.production". Any edit to the file then changes the hash. This catches variables nobody remembered to declare, but it also invalidates the cache when you change values that don't affect the output.
A shared named input
Repeating the same variable list on every target leads to drift. Define the list once in nx.json under namedInputs, for example "buildEnv": [{"env": "API_URL"}, {"env": "NODE_ENV"}, "{projectRoot}/.env"]. Then reference it by name: "inputs": ["default", "buildEnv"]. Adding a variable to buildEnv updates every build target that uses it.
Runtime inputs
{"runtime": "node --version"} hashes the output of a command. Use it for values that no file records, such as the toolchain version or the platform (node -p "process.platform + '-' + process.arch").
Nx runs the command on every hash calculation, so a slow command slows down each run. The output must also be stable. A timestamp or random value in the output gives every run a new hash, and the cache never hits. The cost is worth it when the value really changes the artifacts, such as a native addon compiled for one architecture or a bundle that depends on the Node.js version.
{
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"sharedGlobals": [],
"production": ["default", "!{projectRoot}/**/*.spec.ts"],
"buildEnv": [
{ "env": "API_URL" },
{ "env": "NODE_ENV" },
"{projectRoot}/.env",
"{workspaceRoot}/.env.production",
{ "runtime": "node --version" },
{ "runtime": "node -p \"process.platform + '-' + process.arch\"" }
]
},
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production", "buildEnv"]
},
"test": {
"cache": true,
"inputs": ["default", "^production", { "env": "API_URL" }]
}
}
}
An nx.json that defines a shared buildEnv named input with env, .env file and runtime entries, uses it in the build target default, and adds a single env input directly to the test target. The same inputs array works in a project.json target.
Which input strategy should you choose: individual variables, whole .env files, or runtime inputs?
Every strategy trades false cache hits against lost cache hits. Too few inputs and a task restores artifacts built for a different config. Too many, or volatile ones such as timestamps, commit SHAs or CI build numbers, and every run gets a fresh hash. That is safe, but the cache stops being useful.
| Strategy | Strength | Failure mode | Best for |
|---|---|---|---|
Individual env inputs |
Precise. Only the variables a task actually reads affect its hash | Drifts when code starts reading a new variable that nobody added to the inputs | Build-time config with a small, stable set of variables |
Whole .env file inputs |
Simple, and new variables are covered automatically | Over-invalidates when unrelated lines change, such as a comment or another service's port | Small projects, or files scoped to one project |
runtime inputs |
Captures state that variables cannot, such as toolchain or OS output | Spawns a process for every hash and can be nondeterministic | Native builds where the toolchain changes the output |
Use per-variable inputs when the variable list is short and code review catches new process.env reads. If nobody owns that list, it will fall out of date.
Use whole-file inputs only for files that are committed and shared. A git-ignored file that is still hashed, such as .env.local, exists on laptops but not in CI. Local hashes then never match CI hashes, so the remote cache misses for everyone.
Use runtime inputs as a last resort. Choose commands that are fast and give stable output: a compiler version string, not date or git rev-parse HEAD.
Why should backend services read config at run time instead of build time?
The cheapest env input is the one you never declare. If a backend service reads configuration when the process starts instead of when it is built, the build output does not depend on the environment. One cache entry then serves dev, staging and production, and the build target's env input list shrinks to the few variables that actually change compiled output, such as NODE_ENV if your bundler branches on it.
This costs some development work. You need a config loader that reads process.env once at startup, coerces types, applies defaults, and fails fast with a clear message when a required value like DATABASE_URL is missing or malformed. Startup validation matters because a bad value is no longer caught at build time. It surfaces when the process boots, so the check has to run before the service accepts traffic.
Frontend bundles are the limit. Browser code cannot read the server's environment, so bundlers inline values at build time, and those values must stay declared as inputs. A common workaround is to serve a small runtime config file next to the static assets.
The savings come from building once and promoting the same artifact through every environment.
Illustrative estimate (assumed numbers, not a benchmark):
- Environments: E = 3
- Affected services per merge: S = 10
- Build time per service: B = 2 minutes
- Merges per day: M = 20
Rebuild time avoided per day = (E − 1) × S × B × M = 2 × 10 × 2 × 20 = 800 build-minutes.
This approach also prevents stale-artifact incidents, where a build compiled with staging values is deployed to production.
// config.ts: read process.env once at startup, never at build time.
// The compiled output is identical for dev, staging and production.
export interface Config {
databaseUrl: string;
port: number;
logLevel: 'debug' | 'info' | 'warn' | 'error';
}
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing required env var ${name}`);
return value;
}
export function loadConfig(): Config {
const databaseUrl = required('DATABASE_URL');
// Reject malformed values here, not later when the first query runs.
if (!/^postgres(ql)?:\/\//.test(databaseUrl)) {
throw new Error('DATABASE_URL must start with postgres:// or postgresql://');
}
const port = Number(process.env.PORT ?? '3000');
if (!Number.isInteger(port) || port <= 0) {
throw new Error(`PORT must be a positive integer, got "${process.env.PORT}"`);
}
const logLevel = process.env.LOG_LEVEL ?? 'info';
if (!['debug', 'info', 'warn', 'error'].includes(logLevel)) {
throw new Error(`LOG_LEVEL must be one of debug|info|warn|error, got "${logLevel}"`);
}
return Object.freeze({ databaseUrl, port, logLevel: logLevel as Config['logLevel'] });
}
// main.ts: validate before listening, so a bad value stops the process before it accepts traffic.
// try { const config = loadConfig(); startServer(config); }
// catch (err) { console.error((err as Error).message); process.exit(1); }
A startup config loader that reads, coerces and validates environment variables when the process boots, so one cached build artifact can run unchanged in every environment.
How do you keep secrets out of the Nx cache and task logs?
An Nx cache entry contains more than build artifacts. It also stores the task's terminal output, which Nx replays on every cache hit. With a remote cache, one entry can be restored on any branch, any developer's laptop, and any CI pipeline that has read access. A secret written into an artifact or printed to stdout during a production build can then appear on a feature-branch CI runner or in a contractor's terminal. Rotating the credential does not delete copies already sitting in the cache.
Rules for sensitive values
- Never write secrets into build outputs. A bundle, generated config file or Docker build context should not contain credentials. Anything listed in a target's
outputsis archived exactly as written. - Do not echo secrets in task logs. Remove debug lines that print the environment, and check that tools do not dump resolved config on failure. Cached logs are replayed verbatim.
- Pass secret values only to run or deploy targets that are not cached. The build stays deterministic and shareable. The secret is injected at the point where the code actually talks to the database or cloud API.
When to turn caching off
Setting cache: false on a target removes the risk entirely, but the task then re-runs every time. That cost is acceptable for deploy, migrate and seed targets: they are fast, have side effects, and should never be skipped anyway. For a build target, disabling the cache is usually a sign that it is reading secrets it should not need. Fix the target first. Only disable caching if a build truly cannot avoid embedding a sensitive value, and accept the slower runs as the price of keeping that value out of shared storage.
// apps/api/project.json (Nx accepts comments in project.json)
{
"name": "api",
"targets": {
"build": {
// Cached and shareable: the build never needs DATABASE_URL or API keys.
// Everything under outputs is archived as-is, so it must stay secret-free.
"executor": "nx:run-commands",
"options": {
"command": "tsc -p apps/api/tsconfig.app.json"
},
"cache": true,
"inputs": ["production", "^production"],
"outputs": ["{workspaceRoot}/dist/apps/api"]
},
"migrate": {
// Side effects plus a live credential: never replay this from cache.
// DATABASE_URL comes from the CI secret store at run time, and the
// script must not print it.
"executor": "nx:run-commands",
"options": {
"command": "node dist/apps/api/migrate.js"
},
"dependsOn": ["build"],
"cache": false
},
"deploy": {
// Secrets are injected only here, where the code talks to the cloud API.
// With cache: false, nothing this target logs is stored or shared.
"executor": "nx:run-commands",
"options": {
"command": "./scripts/deploy.sh api"
},
"dependsOn": ["build", "migrate"],
"cache": false
}
}
}
The build target is cached and never needs credentials, while the migrate and deploy targets that receive secrets at run time have caching turned off, so their logs and side effects are never stored or replayed from a shared cache.
How do you debug a suspected bad cache hit and keep CI and local environments aligned?
Debugging a suspected bad hit
Work from cheapest to most disruptive:
- Compare hashes between the two runs. Run the same target where the output was correct and where it was wrong, then compare the task hashes. If the hashes match but the outputs should differ, an input is missing from the hash. Inspect the task's hash details, available through your version's task details view or verbose output, and look for the variable or file you expected to see. If it is absent, you have found the gap.
- Bypass the cache once. Re-run with
--skip-nx-cache. If the fresh output is correct, the cache served a stale artifact. If it is still wrong, the problem is in the build itself and the cache is not involved. - Clear local state.
nx resetremoves the local cache and stops the daemon. This rules out leftover artifacts from earlier experiments. - Suspect the daemon. A long-running daemon can keep the environment it started with. If you changed a shell variable or a
.envfile and the hash did not move, restart the daemon. You can also run withNX_DAEMON=falseto confirm.
Prevention
- Set every declared variable explicitly in CI. Do not rely on runner defaults.
- Commit a
.env.examplethat lists every variable name, and git-ignore the real.envfiles. - Treat an undeclared variable that changes output in CI as a correctness bug, not a cache quirk.
Nx has changed how it loads dotenv files and which inputs it includes by default across versions. Check your version's docs and read the actual hashes rather than trusting memory. When every input is declared, a mismatch shows up as a hash difference you can read, so you rarely have to guess at hidden state.
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, 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.