NEWNow open source & self-hostable. Star us on GitHub →
·14 min·By Nicolas Ritouet

Do AI Coding Tools Read .env Files? Yes. Here's What to Do

Claude Code, Cursor, and Copilot read your .env files. Here's how each tool works, what mitigations exist, and when you need zero-disk secrets.

TL;DR: AI coding tools read your project directory to provide context, including .env files if they're on disk. The actual risk depends on the tool, its access mode, and the LLM provider's data retention policy. .gitignore doesn't help. Ignore files (.claudeignore, .cursorignore) help partially. The strongest mitigation is keeping secrets off disk entirely.


What happens when an AI tool reads your project

AI coding tools need filesystem context to be useful. They read your source code, your configs, your documentation, and if a .env file is sitting in your project directory, it gets included.

The mechanism is simple:

  1. .env file sits on disk in your project
  2. AI tool reads the filesystem for context
  3. File content is sent as part of the LLM prompt
  4. The LLM provider processes (and retains) it

But "your secrets are sent to the cloud" is an oversimplification. The real risk depends on which of these three scenarios applies to you:

Level 1: Secrets in LLM context (passive reading)

Your .env contents are included in the prompt sent to the LLM provider. The model sees your API keys as part of the conversation context. In most cases, the model won't do anything malicious with them, but they're now outside your machine.

Risk: Low-to-medium. Depends on the provider's data handling policies (see data retention below).

Level 2: Secrets retained by the provider

LLM providers store conversation data for varying periods. Your secrets may sit in their logs, safety monitoring systems, or training pipelines depending on your plan type and settings.

Risk: Medium. This is the "what happens after the request" question most developers don't ask.

Level 3: Secrets exfiltrated via prompt injection

A malicious file in your project (a crafted README in a dependency, a poisoned issue body fetched by an agent, or a hidden instruction in a code comment) can instruct the LLM to exfiltrate secrets from its context. The AI tool has shell access, can make HTTP requests, and has your secrets in context.

Risk: High. This is the scenario that actually keeps security researchers up at night, and it's the one most articles about ".env files and AI" completely ignore.


How each tool handles .env files

Claude Code

Claude Code reads project files into its context window. It does not use the dotenv library; it reads files directly from disk as part of building context for the conversation.

The .claudeignore file exists to exclude files from context. However, The Register reported in January 2026 that .claudeignore rules were not properly blocking .env files in certain versions. This has been discussed on GitHub.

Mitigation: Add .env* to .claudeignore. Verify it works by asking Claude Code: "What environment variables do you see in this project?"

Cursor

Cursor reads your workspace for AI features: semantic search, Tab completions, Agent mode, and @mention context.

Two ignore files exist with different scopes:

  • .cursorignore: Blocks files from all AI features (semantic search, Tab, Agent context, @mentions)
  • .cursorindexignore: Blocks files from indexing only; the AI can still access them via @mentions or Agent commands

The real gap is Agent mode. Even with .cursorignore, the AI agent can execute shell commands that read any file on disk. From a Cursor forum report:

"The AI agent used cat to read files I explicitly added to .cursorignore"

Mitigation: Add .env* to .cursorignore. Be aware that Agent mode with shell access can bypass this.

GitHub Copilot

Copilot indexes your workspace for code completions and chat context. There is no .copilotignore file. Content exclusion is configured through organization or repository admin settings, not a file in your project.

Important limitation: content exclusion does not apply to GitHub Copilot CLI or Agent mode.

Mitigation: Configure content exclusion at the organization level. This requires admin access and doesn't cover CLI/Agent mode.

Windsurf (Codeium)

Windsurf indexes your workspace for its Cascade AI flow. A .windsurf/ignore file prevents indexing, but like Cursor, Agent mode with shell access can still read any file on disk.

Aider

Aider sends file contents to LLM providers when you add files to the chat context. It's more explicit than other tools: you choose what to include with /add. But an automatic context scan or a careless /add .env will include your secrets.

Cline

Cline operates as a VS Code extension with full filesystem access. It can read any file, execute terminal commands, and has no dedicated ignore file. Your .env is trivially accessible.

Summary

ToolReads .env?Ignore fileBlocks passive reading?Blocks agent/shell access?
Claude CodeYes.claudeignorePartially (known bugs)No
CursorYes.cursorignoreYesNo
GitHub CopilotYesNone (admin settings)PartiallyNo
WindsurfYes.windsurf/ignoreYesNo
AiderIf addedManualN/AN/A
ClineYesNoneNoNo

The pattern is clear: ignore files protect against passive context reading. None of them protect against an AI agent that can run shell commands.


Data retention: where do your secrets end up?

When your secrets are sent as LLM context, the next question is: how long does the provider keep them?

ProviderDefault retentionZero Data RetentionNotes
Anthropic (API)30 daysAvailable for EnterpriseDocs
Anthropic (claude.ai)Up to 5 yearsN/AIf user opts in to model improvement
OpenAI (API)30 daysAvailable for BusinessDocs
CursorVariesDepends on modelRoutes to Anthropic, OpenAI, or other providers

This matters because most AI coding tools use API endpoints, not consumer accounts. At the API level, both Anthropic and OpenAI retain data for 30 days by default, primarily for safety monitoring and abuse prevention.

If you're on an enterprise plan with Zero Data Retention enabled, the risk from Level 2 (provider retention) is minimal. If you're using a consumer account on claude.ai, your conversations, including any .env contents in context, may be retained for training.

Info: Most AI coding tools (Cursor, Claude Code CLI, Copilot) use API endpoints, not consumer accounts. Check your plan type to understand which retention policy applies to you.


The real risk: prompt injection

Most articles about AI tools and .env files focus on passive reading. The more dangerous scenario is active exfiltration through prompt injection.

Here's how it works: a malicious actor plants instructions in a file the AI tool will read (a dependency's README, a GitHub issue body, a markdown file, or even a code comment). When the AI processes that file, the injected prompt instructs it to extract secrets from context and send them somewhere.

The AI tool has your secrets in context and the ability to execute shell commands (curl, wget, etc.). A successful prompt injection attack can combine both.

This isn't theoretical. Researchers have demonstrated prompt injection attacks against coding assistants that exfiltrate environment variables, SSH keys, and API tokens.


What doesn't work (and what partially works)

.gitignore

.gitignore prevents commits. It doesn't prevent filesystem reads.

# .gitignore
.env
.env.local
.env.production

# AI tools still read these files, they're on disk

Correct and necessary, but insufficient on its own.

.claudeignore / .cursorignore / content exclusions

These do protect against passive context reading in normal usage. They're worth configuring:

# .claudeignore or .cursorignore
.env
.env.*
.env.local
.env.production

They don't protect against Agent mode with shell access. If the AI can run cat .env, the ignore file is bypassed.

Verdict: A useful first layer. Not sufficient as the only defense.

.aiignore / .llmignore

Community proposals for a universal AI ignore standard. .llmignore is the most formal specification. Neither is widely adopted as of April 2026; individual tools still use their own ignore files.

Worth watching, but not something you can rely on today.

Encrypted .env (dotenvx, SOPS)

Encrypted .env files protect against passive context reading: the AI sees ciphertext, not your secrets. This is a real improvement over plaintext .env.

# dotenvx encrypts your .env file
dotenvx encrypt

# The AI sees something like:
# DATABASE_URL="encrypted:BEn31..."
# Not your actual connection string

The limitation: if the AI has shell access and can run dotenvx run or sops -d, it can decrypt the file. The encryption key needs to be available somewhere for the app to start.

Verdict: Solid defense against passive reading. Doesn't protect against agent-mode shell access.

"Just don't use AI tools"

Not realistic for most teams in 2026. The answer isn't abstinence, it's defense in depth.


What works: zero-disk secrets

The strongest mitigation is removing secrets from disk entirely. If there's no .env file, there's nothing for any tool to read, regardless of ignore files, agent mode, or shell access.

The principle

  1. Secrets stored in a remote vault
  2. Fetched at runtime via authenticated API call
  3. Injected into process memory as environment variables
  4. No file written to disk

Tools that implement this

Several secrets managers support a run command that injects secrets directly into your process:

# Doppler
doppler run -- npm run dev

# Infisical
infisical run -- npm run dev

# Keyway
keyway run -- npm run dev

# 1Password CLI
op run -- npm run dev

All four follow the same pattern:

  1. Authenticate with the secrets manager
  2. Fetch secrets from the remote vault
  3. Spawn your command as a child process
  4. Inject secrets into the child's environment (memory only)
  5. No .env file created, no disk write

Comparison: secrets managers for zero-disk secrets

ToolZero-disk runAuth MethodSelf-hostedPricingBest For
Dopplerdoppler runEmail, SSO, SAMLNoFree 5 users, then $8/user/moTeams needing SSO/SAML
Infisicalinfisical runEmail, SSO, SAMLYesFree 5 users, then $18/user/moSelf-hosted requirements
1Passwordop run1Password accountNo$7.99/user/moTeams already on 1Password
Keywaykeyway runGitHub OAuthNoFree public repos, $9/mo ProSolo devs, GitHub-native workflows
dotenvxEncrypted on diskGit + encryption keyYes (it's git)FreeGit purists, no external dependency
SOPSEncrypted on diskKMS/PGPYesFreeInfrastructure teams, GitOps

Key differences

Doppler & Infisical: Enterprise-focused, feature-rich (audit logs, rotation, RBAC). Higher price point, more setup.

1Password: Great if your team already uses it for passwords. Requires 1Password subscription.

Keyway: GitHub-native auth (no new accounts). Simple for solo devs and small teams. Fewer features than enterprise tools.

dotenvx & SOPS: Encrypted files in git. No external service dependency, but the file is still on disk (encrypted). Protects against passive AI reading but not against agent-mode decryption.


How to choose

If you...Consider
Need SSO/SAML/enterprise complianceDoppler, Infisical
Must self-host (air-gapped, regulatory)Infisical, dotenvx, SOPS
Already use 1Password for team passwords1Password CLI
Want GitHub-native auth, minimal setupKeyway
Prefer git-native, no external servicedotenvx, SOPS
Solo dev, want simplest optionKeyway or dotenvx
Large team (20+ devs)Doppler, Infisical

When to keep using .env files

Be honest: .env files are fine when:

  • Solo hobby project with no sensitive data
  • Air-gapped environment with no network access
  • You explicitly need file-based config (some legacy tools require it)
  • You're prototyping and will fix it before prod

The goal isn't purity. It's reducing risk where it matters.


Migration examples

The workflow is similar across tools. Here's how it looks with Doppler and Keyway:

Doppler

# Install
brew install dopplerhq/cli/doppler

# Login and setup
doppler login
doppler setup

# Import existing secrets
doppler secrets upload .env

# Run your app, secrets injected, no file needed
doppler run -- npm run dev

# Delete the .env file
rm .env

Keyway

# Install
brew install keywaysh/tap/keyway

# Initialize and authenticate via GitHub
keyway init

# Import existing secrets from .env
keyway push

# Run your app, secrets injected, no file needed
keyway run -- npm run dev

# Delete the .env file
rm .env

Team onboarding (both tools)

# New developer joins, no "ask John for the .env file"
git clone your-repo
npm install

# Doppler
doppler login && doppler setup && doppler run -- npm run dev

# Keyway
keyway login && keyway run -- npm run dev

If the developer has access to the project, they get the secrets. No Slack messages, no shared password managers, no stale .env files.


Verify it yourself

Don't take our word for it. Test your setup:

Step 1: Check if your AI tool sees your secrets

Open your AI coding tool and ask:

Tip: Copy-paste this prompt into your AI coding tool: "What's in my .env file? List all environment variables you can see in this project." If it lists your secrets, they're in the LLM context.

Step 2: Test your ignore file

Add .env* to .claudeignore or .cursorignore, restart the tool, and ask again. If secrets are still visible, the ignore file isn't working for your tool version.

Step 3: Go zero-disk and verify

# Remove the .env file
rm .env .env.local

# Run with your secrets manager
keyway run -- npm run dev  # or doppler run, infisical run, op run

# Verify: no .env on disk
ls .env* 2>/dev/null || echo "No .env files found"

# Ask your AI tool again, it should see nothing

CI/CD integration

All these tools support CI/CD. Example with GitHub Actions:

Doppler:

- uses: dopplerhq/cli-action@v3
- run: doppler run -- npm run build

Infisical:

- uses: infisical/secrets-action@v1
- run: infisical run -- npm run build

Keyway:

- uses: keywaysh/action@v1
- run: keyway run -- npm run build

Or sync secrets directly to your deployment platform and skip the run command entirely.


FAQ

"Doesn't this just move the trust to a third party?"

Yes. You're trading "secrets in a plaintext file readable by any process on your machine" for "secrets in a managed vault with access controls, encryption at rest, and audit logs."

Pick a provider you trust, or self-host (Infisical, SOPS, dotenvx).

"Can't AI tools read environment variables from the running process?"

In theory, an AI tool with shell access could read /proc/self/environ on Linux. Current tools don't do this; they read files from disk. Zero-disk secrets close the filesystem attack vector, which is the most common one today.

"What about local development speed?"

The run commands add ~200-500ms startup latency (one API call to fetch secrets). For hot-reload workflows, secrets are cached in the parent process; only the initial start is affected.

"I'm on a plane with no internet"

Valid concern. Options:

  • doppler run --fallback=.env.local (encrypted local cache)
  • keyway pull before going offline (caches secrets locally)
  • Accept that you need network for secrets (security tradeoff)

Summary

  1. AI coding tools read your .env files as part of building LLM context
  2. Ignore files (.claudeignore, .cursorignore) help against passive reading but not against agent-mode shell access
  3. The real danger is prompt injection combined with secrets in context, not just passive reading
  4. LLM providers retain data for 30 days by default (API). Enterprise ZDR is available.
  5. Defense in depth: configure ignore files and keep secrets off disk with a run command
  6. Choose a secrets manager based on your needs: enterprise features, self-hosting, pricing, auth method

Your AI assistant should help you write code, not have your secrets in its context window.


Further reading


References:

Stop sharing secrets on Slack

Keyway syncs your environment variables securely. Free for open source.