claude/for
Search
Subscribe
Claude Code

Claude Code API keys and .env files: safe setup guide

Store a Claude Code project API key in a local .env file, prove Git ignores it, test without exposing it, and rotate it after a leak.

Put a project API key in .env only after .gitignore covers that file and you have verified the rule with Git. Use a dedicated low-privilege key, add a provider-side spending limit when available, and test it without ever printing the value.

A .env file keeps a credential out of source code. It does not encrypt the credential or stop every local process from reading it. This is an independent, unofficial guide; claude/for is not affiliated with Anthropic, GitHub, or any API provider.

First, know which API key you have

Two different credentials are easy to confuse:

  • ANTHROPIC_API_KEY authenticates the Claude Code CLI itself to Anthropic.
  • A project key, such as SEARCH_API_KEY, lets your program call a third-party service.

This walkthrough is mainly about the second kind. Anthropic's authentication documentation says an approved ANTHROPIC_API_KEY takes priority over subscription login in the CLI. That can move Claude Code onto metered API billing. Run /status to check the active credential, or read the Claude Code pricing guide before changing authentication.

Claude Code does not automatically load every .env file. Your application, shell, IDE, direnv, or a dotenv loader may load it. Anthropic's error guide specifically warns that these tools can leave a stale key active.

If project folders and terminal commands are new to you, start with Claude Code for non-developers, then return here for the credential setup.

Create the smallest useful key

Treat an API key like a keycard, not a label. Anyone or any process holding it may be able to use its granted authority.

Create a separate key for this project rather than reusing your personal all-purpose key. Give it a descriptive name, choose read-only access or the narrowest resource and action scopes offered, add an expiry, and set a quota or spending alert where the provider supports those controls.

Those controls differ by provider. A rate limit caps throughput; it is not necessarily a spending cap. Anthropic currently ties API keys to Console Workspaces. Its Workspace documentation documents Workspace rate limits, spending limits, alerts, and key revocation, but not a universal endpoint scope or hard budget attached to every Anthropic key.

Add the ignore rule before the secret

Create or edit .gitignore before creating .env:

.env
.env.*
!.env.example

Then create a shareable .env.example containing the variable name only:

DEMO_API_KEY=

Your local .env gets the real development value. Do not put that value in .env.example, CLAUDE.md, a prompt, or .claude/settings.json. Anthropic's environment-variable reference says project .claude/settings.json is intended for source control.

Order matters. Git's official .gitignore documentation says ignore rules do not affect files already tracked. Adding .env to .gitignore after a commit prevents neither the earlier commit nor its copies from containing the key.

Prove Git is ignoring .env

Tested with Git 2.46.0 in a fresh disposable repository on July 12, 2026. The .env contained only demo_old_not_a_real_secret, an explicitly synthetic value that cannot access a service.

Run:

git check-ignore -v .env
git status --short --ignored -- .env .env.example .gitignore
git ls-files .env

Our observed status was:

?? .env.example
?? .gitignore
!! .env

?? means the two safe files were untracked. !! means Git was ignoring .env. git ls-files .env printed nothing, confirming that path was not tracked.

Now stage only the files you intend to share:

git add .gitignore .env.example
git diff --cached --name-only
git diff --cached

The staged path list should contain .gitignore and .env.example, never .env. Inspect the full staged diff before committing. This is the same evidence-first habit used in the guide to make Claude Code verify its work: define the expected result, run the check, and read the output.

After committing those two safe files, check whether .env ever appeared at that path:

git log --all --full-history -- .env

Our disposable repository returned no commits. That proves only that .env is absent from this local repository's history. It cannot detect a key pasted into another file, commit message, issue, log, screenshot, remote fork, or clone.

Test the key without revealing it

Let your application's normal runtime load .env. Ask it to report only whether the variable exists and whether a small read-only request succeeded. A useful result looks like this:

DEMO_API_KEY present: yes
Read-only test: success

Do not use echo, paste the value into a prompt, include it in an error message, or capture it in a screenshot. A successful request proves only that the credential worked at that moment. It does not prove the scope is narrow, the key is absent from history, or nobody else has used it.

Rotate a key without losing control

For planned rotation, keep the old key valid until the replacement works:

now

Create the replacement

Use the same or narrower permissions, a clear name, and provider-side limits.

now

Update the local consumer

Replace the value in .env without printing it, then restart the process so it reloads the environment.

next

Run one low-impact check

Confirm a read-only request succeeds and record only the status, never the credential.

next

Revoke the old key

Disable it at the provider, then confirm the old value fails while the replacement still succeeds.

If you suspect exposure, change the order: revoke or disable the old key first, even if that causes brief downtime. Then create, deploy, and test its replacement.

If a key reached a commit

Deleting .env from the latest version is not enough. GitHub's sensitive-data removal guide says to revoke or rotate a credential first. Then review the provider's usage, access logs, and billing from the likely exposure time.

Next, remove the value from the current tree and assess every place it may remain: Git history, pull requests, forks, collaborators' clones, CI logs, issues, and screenshots. A history rewrite changes commit hashes and can reintroduce the secret if an old clone pushes again, so coordinate it instead of improvising a force push.

GitHub push protection can block supported credentials before a push, and secret scanning can alert on documented patterns. Neither provides a universal guarantee: detection depends on supported patterns and repository coverage, and authorized users may be able to bypass a warning. A private repository reduces visibility; it is not a secret manager.

Know what .env cannot protect

An ignored .env is still a plaintext local file. A person or process with sufficient read access can see it. A prompt saying “never reveal this key” is an instruction, not a technical boundary.

Claude Code permission rules can deny Read(.env), but Anthropic's permissions guide says arbitrary Python or Node subprocesses may still read files. For unattended or production work, use a secret manager, tighter sandbox boundaries, or a proxy that injects credentials without exposing them to the agent. The Routines guide explains why a cloud run cannot rely on your laptop's ignored .env.

If you are still deciding whether a raw project key is the right connection at all, read the Claude connectors guide before adding another credential. An OAuth-based connector can avoid handing a raw project key to the local workflow, although its permissions still need review.

Does Claude Code automatically read a .env file?

No. A project runtime, shell plugin, IDE, direnv, or dotenv tool may load the file. Claude Code can read project files when its tools and permissions allow, but .env is not universally loaded at startup.

Is a .env file safe if it is in .gitignore?

It is safer from accidental Git tracking, not encrypted or inaccessible. Verify the ignore rule before the first commit, keep local access narrow, and use a secret manager for shared, unattended, or production systems.

What should I do if I committed an API key to GitHub?

Revoke or rotate the key first. Then review usage, replace the credential, remove it from the current tree, assess Git history and copies, and follow GitHub's coordinated cleanup guidance if history must be rewritten.

One Claude move in your inbox, every Sunday

Four minutes, tested on a real job, then back to your weekend. Free.