Terminal showing a package reading a .env file, a dotenvx-encrypted key, a VITE_ secret in the bundle and gitleaks blocking a commit

Keeping application keys in a plaintext .env file is no longer enough: a malicious npm package, an AI agent with access to the repository or an unreviewed git add can all read it. We tested it in a lab with a simulated package, dotenvx, Vite, gitleaks and git-filter-repo, and found a detail most guides leave out: encrypting the .env does not protect the key once the application loads it.

Key points in 30 seconds

  • A plaintext .env is as private as a password on a sticky note. Any code with access to the project folder can read it: an npm package you installed this morning, the AI agent you gave repository access to, or you with a careless git add ..
  • This is not theoretical: in March 2026 researchers found pino-sdk-v2, a copy of a popular Node.js logger that read .env files on require() and sent them to a Discord webhook. GitGuardian counted 28.65 million new secrets in public GitHub commits in 2025, 34% more than the year before.
  • Encrypting .env values with dotenvx works: in our test, a package reading the file only saw ciphertext. But the private key has to leave the project folder, or the package takes it too.
  • What encryption does not protect: with dotenvx run, the decrypted key ends up in process.env, and a malicious package inside your application reads it anyway. You still need narrowly scoped keys, rotation and dependency hygiene.
  • Two more traps, verified: variables prefixed with VITE_ (or NEXT_PUBLIC_) end up in the JavaScript every visitor downloads, and if a key reaches a published commit, revoke it before cleaning history.

The .env file has been the standard way to store application configuration for years: add it to .gitignore and consider the problem solved. For configuration (a port, a URL, a log level) that is still fine. For real secrets (the payment gateway key, the database password, the cloud provider token) it falls short, because two things have changed: what we run on our machines (hundreds of dependencies nobody reviews) and who reads our files (AI agents that explore the whole project to do their job).

We built a lab with Node.js 24 to check each risk and each fix, using test keys.

How secrets leak from a .env file

1. The packages you install

In March 2026, SafeDep found pino-sdk-v2: an almost identical copy of pino, a Node.js logger with nearly 20 million weekly downloads, complete with its README and documentation. The only difference was obfuscated code in lib/tools.js that searched .env, .env.local, .env.production, .env.development and .env.example for keys and sent them to a Discord webhook. It did not use install scripts, which is what many scanners watch: it ran the moment the code called require().

In September 2025, the Shai-Hulud worm went further: it installed TruffleHog, a legitimate secret-scanning tool, to sweep the disk and environment variables of infected machines for npm, GitHub and cloud tokens, then used them to publish infected versions of other packages.

We reproduced it with a simulated “logging” package that reads the project’s .env files when loaded (it only prints them):

Terminal: a simulated package reads the plaintext .env; after dotenvx encryption it only sees ciphertext, but it also reads the .env.keys file next to it
Secrets in .env files: how they leak through npm, AI agents and Git, and how to protect them

With a plaintext .env, the package grabbed the Stripe key and the database password without doing anything special: it just read a text file.

2. The AI agent in your editor

Coding agents read files to do their job; that is what they are for. Ask one to “find out why the database connection fails” and it will look at the project configuration, and if it can read .env, it will see the password even though you did not ask for it. Whatever it reads can end up in the conversation history, in a log or, if the agent has tools connected, somewhere else.

Ignore files help, but they are not airtight. Cursor’s own documentation says so: .cursorignore blocks access from the agent, autocomplete and mentions, but “the terminal and MCP server tools used by Agent cannot block access” to those files. A cat .env from the agent’s terminal still works. Other agents support read-deny rules in their settings; they are a useful seatbelt, not a guarantee.

AI tooling also leaks secrets on its own: GitGuardian found 24,008 secrets in MCP server configuration files published on GitHub, 2,117 of them valid. If you connect agents to tools, audit the MCP servers you give them as well; Cloud Privado has a guide (in Spanish) on how to audit an MCP server before connecting it to your agents.

3. Git, sooner or later

Everyone knows .env is not committed. And yet it is: someone removes the line from .gitignore, forces a git add -f for a test or runs git add . in a hurry. GitGuardian’s State of Secrets Sprawl 2026 report gives the scale:

  • 28.65 million new secrets in public GitHub commits in 2025, up 34% on 2024.
  • 64% of the secrets confirmed valid in 2022 still worked in January 2026. A leaked key does not expire on its own: it stays open for years.
  • Internal repositories hold about six times more hardcoded secrets than public ones. A private repository is not a protection.

The frontend trap: VITE_ and NEXT_PUBLIC_

Vite only exposes variables starting with VITE_ to browser code; Next.js, those starting with NEXT_PUBLIC_. What many people miss is the flip side: those variables are copied into the JavaScript every visitor downloads. We checked with Vite 8.4.0:

Terminal with Vite 8.4.0: the VITE_-prefixed key appears in the built JavaScript while the unprefixed server key does not
Secrets in .env files: how they leak through npm, AI agents and Git, and how to protect them

The VITE_STRIPE_SECRET_KEY showed up verbatim in dist/assets/index-….js. The unprefixed server key did not. In February 2026, Sprocket Security described a real case: a Vite configuration that shipped live AWS keys and a CircleCI token in public JavaScript, which led them to production code in S3 and full control of the deployment pipeline.

The rule: if a variable has a public prefix, anyone can read it, and encrypting it does not help because it is decrypted at build time and published anyway. If the browser needs something that requires a secret, route the call through your server.

One more warning for Vite developers: do not expose the dev server to the network. In April 2026, CVE-2026-39364 (severity 7.5) was published, allowing file reads from the dev server by bypassing server.fs.deny, in versions from 7.1.0 up to before 7.3.2 and 8.0.5. In August 2026, F5 Labs recorded a mass-scanning campaign looking for exactly that on exposed servers: .env files, AWS keys, Azure tokens and Terraform state files.

Option 1: encrypt .env values with dotenvx

dotenvx comes from the author of the original dotenv package. It encrypts .env values with public-key cryptography and decrypts them only when the application starts:

npm install -g @dotenvx/dotenvx
dotenvx encrypt -k STRIPE_SECRET_KEY -k DATABASE_URL   # -k: only these keys
dotenvx run -- node index.jsCode language: CSS (css)

In our test (dotenvx 2.38.2), the .env ended up with a public key at the top, PORT=3000 readable and the secrets as encrypted:BNNEmGo…. Starting the app without dotenvx, using node --env-file=.env, it only saw ciphertext, and so did the package reading the file.

The detail that decides everything: the private key is stored in .env.keys, in the same folder. Our simulated package read it just like the .env. Move it out:

echo ".env.keys" >> .gitignore
mkdir -p ~/.config/dotenvx
mv .env.keys ~/.config/dotenvx/shop.keys
dotenvx run -fk ~/.config/dotenvx/shop.keys -- node index.jsCode language: JavaScript (javascript)

Without the private key, dotenvx run fails with “DECRYPTION_FAILED”. In CI or production, the private key goes in the DOTENV_PRIVATE_KEY variable of the platform’s secret store, and the encrypted .env can be committed.

What encryption does not protect

This is the part most guides skip. With dotenvx run, the application receives the key decrypted in its environment variables. We changed the simulated package to read process.env instead of the file:

Terminal: with dotenvx run, the simulated package reads the decrypted Stripe key from the process environment
Secrets in .env files: how they leak through npm, AI agents and Git, and how to protect them

It read the key in plaintext. Encryption protects the file on disk, the repository and scanners sweeping the folder; it does not protect against code already running inside your application, because that code sees what your code sees. Against that, the defences are different:

  • Narrowly scoped keys: the development key only for the test environment; the database credential only for that database and without admin rights.
  • Rotation: keys that expire on their own or change often. A secrets manager with short-lived credentials automates it.
  • Dependency hygiene: npm ci with the lockfile, reviewing new packages before adding them and distrusting lookalike names (pino-sdk-v2 is not pino).
  • Keep as few production secrets as possible on laptops. The best secret is the one that is not on your machine.

Option 2: references to a secrets manager

The other route is a .env with no secret values at all, only references that a tool resolves at startup:

# .env with 1Password references
STRIPE_SECRET_KEY=op://dev/stripe/secret-key
DATABASE_URL=op://dev/postgres/url

op run --env-file=.env -- node index.jsCode language: PHP (php)

op run resolves each reference in your vault, passes the values only to that process and, by default, masks secrets if the process prints them. Equivalent tools: the Bitwarden Secrets Manager CLI (bws run), Infisical (infisical run) or OpenBao with its agent. With a self-hosted manager, keys never leave your infrastructure; Cloud Privado keeps an index of self-hosted software tested in its lab (in Spanish).

Another free option widely used by sysadmin teams is SOPS with age: it encrypts values in YAML, JSON or .env files and integrates with Git and cloud KMS services.

The same caveat applies: the reference protects the file, but the process gets the key in plaintext.

What about node –env-file?

Node.js 20.6 added the --env-file flag, and Node 21.7 (backported to 20.12) added process.loadEnvFile(). Together they replace the dotenv package in most projects, which means one less dependency to trust. But they do not change security: the file is still plaintext. It is a dependency improvement, not a security one.

Keep it out of Git: gitleaks before every commit

gitleaks checks staged changes and blocks the commit if it finds a key. As a Git hook:

cat > .git/hooks/pre-commit <<'EOF'
#!/bin/sh
gitleaks git --pre-commit --staged --redact --verbose
EOF
chmod +x .git/hooks/pre-commitCode language: JavaScript (javascript)
Terminal: gitleaks 8.30.1 finds three keys and blocks the commit; git-filter-repo 2.47 removes the .env from history
Secrets in .env files: how they leak through npm, AI agents and Git, and how to protect them

In our test (gitleaks 8.30.1) it detected all three keys in the .env (AWS, secret key and Stripe) and the commit was not created. Two caveats:

  • Older tutorials use gitleaks protect --staged. The detect and protect commands were deprecated in 8.19.0: they still work but are hidden from the help. Use gitleaks git.
  • A local hook can be skipped with git commit --no-verify, and it only exists on the machine where you installed it. Add it to CI too and enable your forge’s push protection for secrets (GitHub, GitLab, or Forgejo with a workflow that runs gitleaks).

Already pushed? Revoke first, clean up later

If a key reached a published commit, treat it as stolen: revoke it at the provider and create a new one before touching history. Cleaning the repository is pointless while the key is still active: it may already be in clones, forks, caches or CI logs.

Then, if you want it out of history, GitHub recommends git-filter-repo 2.47 or later:

git filter-repo --sensitive-data-removal --invert-paths --path .env
git push --force --mirror originCode language: CSS (css)

In our test, the git-filter-repo package in Debian 12 does not recognise --sensitive-data-removal: you need 2.47 (via pip, for example). With it, the .env disappeared from every commit. Anyone with a clone must re-clone, and GitHub or your forge may also require cleaning pull request references.

What we would do today

  1. Configuration in .env, secrets not: every secret value either encrypted with dotenvx (with the private key outside the project) or stored as a reference to a secrets manager.
  2. Nothing secret with a VITE_ or NEXT_PUBLIC_ prefix, and the Vite dev server patched and not exposed.
  3. Separate development and production keys, with minimum scope, and production keys off laptops.
  4. Ignore rules for AI agents, knowing they are not airtight, and isolated environments for agents working unattended.
  5. gitleaks in the hook and in CI.
  6. If something leaks: revoke, rotate and only then clean up.

With all this in place a leak can still happen. The difference is that what leaks is ciphertext, a reference or a key you have already revoked.

FAQ

Is using a .env file insecure?

For configuration, no. For plaintext secrets, yes: any code with access to the project folder can read it, including malicious npm packages and AI agents. The fix is to encrypt secret values or replace them with references to a secrets manager.

Does encrypting .env with dotenvx protect against a malicious npm package?

It protects against a package that reads the file, as long as the private key is outside the project folder. It does not protect against a package running inside your application that reads the already-decrypted environment variables: in our test, that package saw the key in plaintext.

Are VITE_ or NEXT_PUBLIC_ variables secret?

No. They are copied into the JavaScript any visitor downloads. In our Vite 8.4.0 test, a VITE_-prefixed key appeared verbatim in the built file. Secrets go without a prefix and only on the server.

How do I stop an AI agent from reading my .env?

Use each tool’s ignore or read-deny rules, such as .cursorignore, knowing they are not airtight: Cursor’s documentation admits they do not block the terminal or MCP tools. The safest approach is a .env with no plaintext secrets and agents working with narrowly scoped development keys.

I pushed a .env to GitHub by mistake. What now?

First, revoke and replace every key it contained, at each provider. Then, if you want, clean history with git-filter-repo 2.47 or later and ask anyone with a clone to re-clone. Cleaning without revoking is useless: the key may already have been copied.

Sources

Scroll to Top