Node.js --env-file: "Cannot find/parse" - Fix .env Loading in CI
Node’s built-in --env-file loads variables from a dotenv file. It fails when the file is missing, when the Node version is too old to support the flag, or when the file has a syntax the parser rejects.
What this error means
A command using node --env-file=.env aborts before your code runs - either "Cannot find" the file, "bad option: --env-file" on an old Node, or a parse error. Locally the .env exists; in CI it is often gitignored and absent.
node: --env-file: .env: not found
# or, on older Node:
node: bad option: --env-file=.envCommon causes
The env file is not present in CI
.env is typically gitignored, so it exists locally but not on the runner. --env-file=.env then fails to find it.
Node is too old for the flag
--env-file landed in Node 20.6 (and stabilised later). On an older runner image the flag is unrecognised and Node aborts.
The file has invalid dotenv syntax
Node’s parser is stricter than some third-party loaders. A stray character or an unquoted value with special characters can make it reject the file.
How to fix it
Provide the env file or use real CI env vars
In CI, prefer injecting variables through the platform’s secrets rather than committing a .env. If you need the file, write it in a step. Use --env-file-if-exists to tolerate its absence.
# tolerate a missing file (Node 22+)
node --env-file-if-exists=.env app.mjs
# or inject vars directly in CI instead of a filePin a Node version that supports the flag
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: node --version # confirm >= 20.6How to prevent it
- Inject secrets via the CI platform; keep
.envout of the repo and CI. - Pin a Node version new enough for
--env-file. - Use
--env-file-if-existswhen the file is genuinely optional.