Skip to the solution
EasyBackend6 min read

What does the Node.js --env-file flag do, and does it replace dotenv?

66 views

The problem

Question presented to candidate: "Every Node project seems to install dotenv. Do you still need it?"

What a strong answer should cover:

  • Since Node 20.6, node --env-file=.env your-script.js loads key-value pairs from a file straight into process.env before your code runs β€” no package required.
  • It is a CLI flag, not an API you call from inside your code β€” so it must be present on every command that starts the process (node, npm start, your Docker CMD), including test runners.
  • --env-file-if-exists is the forgiving variant: it does not error when the file is missing, which matters for environments (CI, a fresh clone) where a .env may not exist.
  • It supports basic KEY=value syntax and # comments; it does not run shell expansion or nested variable interpolation the way some dotenv-adjacent tools do.
  • Existing process.env values (already set by the shell or the orchestrator) are not overwritten by the file β€” the file only fills in what is missing.
  • It does not replace dotenv's whole ecosystem overnight: multi-file layering (.env.local, .env.production), variable expansion, and framework auto-loading are still dotenv-shaped conveniences some projects want.

Clarifying questions expected:

  • "Which Node version is this running on in production?" β€” anything older than 20.6 needs the package.
  • "Does anything rely on interpolated variables inside the .env file?" β€” that is the feature gap.

Code / implementation expected: Optional. Showing the flag and process.env reading it is enough.

  • env-file
  • dotenv
  • configuration
  • cli-flags

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 9 sections

Read the code

Reading a value loaded purely by the flag β€” no package installed
$ cat .env
GREETING=hello

$ node --env-file=.env -e "console.log(process.env.GREETING)"
hello

# The forgiving variant does nothing (no error) when the file is absent:
$ node --env-file-if-exists=.env.missing -e "console.log('still running')"
still running

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 33 of 152 in Node.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Node.js questions
Up nextEasy

What is the purpose of `package-lock.json`?

Continue