How to Do Environment Variable Management on Claude Code
In this article
- How does Claude Code handle environment variables?
- Three practical approaches to environment variable management
- Security considerations when using secrets with Claude Code
- Using CLAUDE.md to document your environment requirements
- Checking your Claude Code usage before long automation runs
- Key takeaways
- Sources
Claude Code reads environment variables from your shell session automatically. Set them with export API_KEY=value before launching, use a .env file loaded by your shell profile, or reference them inside CLAUDE.md so Claude understands your project's required secrets. No plugin needed for basic use. For real-time visibility into how those API-heavy sessions consume your usage limits, Usagebar shows your Claude Code quota directly in the macOS menu bar.
- Claude Code inherits all environment variables present in the launching shell
- API keys passed as env vars are never sent to Claude's context unless you explicitly paste them
- Usage windows reset on a rolling 5-hour basis, making it critical to know your remaining quota before long automation runs
How does Claude Code handle environment variables?
Claude Code is a terminal-based AI agent, so it runs inside your existing shell environment. That means any variable exported in your session is immediately available to subprocesses Claude Code spawns, including build tools, test runners, database clients, and CLI utilities.
Claude itself does not read your environment variables directly into its context window. Instead, the variables are available to the commands Claude executes on your behalf. This is an important distinction: your DATABASE_URL or STRIPE_SECRET_KEY will never appear in Claude's conversation unless you deliberately paste the value.
According to Anthropic's Claude Code documentation, the tool operates as an agentic loop that can run shell commands, edit files, and call external services. All of that happens through your authenticated shell, so environment hygiene matters just as much as it does in any CI/CD pipeline.
Three practical approaches to environment variable management
1. Shell export (simplest, session-scoped)
The most direct method: export variables in your terminal before starting Claude Code.
export OPENAI_API_KEY="sk-..."
export DATABASE_URL="postgres://user:pass@localhost:5432/mydb"
claude
These variables live only in the current session. Close the terminal and they're gone. Good for quick experiments, not ideal for daily workflows.
2. Shell profile or direnv (persistent, project-aware)
For variables you need every time, add them to ~/.zshrc, ~/.bashrc, or use direnv to load a per-project .envrc file automatically when you cd into a directory.
# .envrc (loaded by direnv)
export STRIPE_SECRET_KEY="sk_test_..."
export SUPABASE_URL="https://xyz.supabase.co"
direnv is particularly powerful because it unloads variables when you leave the directory, preventing accidental key leakage across projects.
3. .env file with explicit loading
Many projects already use a .env file for local development. Claude Code can be told about this pattern through your CLAUDE.md project context file:
# CLAUDE.md
## Environment Setup
This project uses a `.env` file. Run `source .env` or use dotenv-cli before
executing any npm scripts. Required variables:
- DATABASE_URL
- NEXT_PUBLIC_API_URL
- STRIPE_SECRET_KEY (server-side only, never expose to client)
When Claude understands which variables are required and which are server-only, it writes safer code, avoiding common mistakes like accidentally referencing a secret key in a client bundle. See the Claude Code .env file management guide for more patterns.
Security considerations when using secrets with Claude Code
Claude Code can read, edit, and create files in your working directory. This creates a few security surfaces worth understanding:
- Never commit .env files. Claude Code will follow your instructions to edit files, and if your
.gitignoreis misconfigured it could stage secrets. Verify.gitignoreincludes.envand.env.local. - Avoid pasting secret values in chat. Anything in the conversation window is part of the context sent to Anthropic's API. Keep secret values in env vars, not in prompts.
- Use read-only credentials where possible. When Claude Code is running database migrations or queries during development, a read-only replica connection string limits blast radius if something goes wrong.
- Rotate keys after a session if you're unsure. If you accidentally printed an API key in a Claude Code response, treat it as potentially logged and rotate it.
These are the same practices recommended for any CI system. Claude Code is effectively an automated agent with filesystem and shell access, so apply the same least-privilege principles you'd use with a GitHub Actions runner.
Using CLAUDE.md to document your environment requirements
The CLAUDE.md file is Claude Code's persistent context for a project. It's one of the most underused features for environment management. By documenting your required variables here, every Claude Code session starts with full awareness of your project's secrets structure, without you needing to re-explain it.
A well-structured environment section in CLAUDE.md might look like:
## Environment Variables
### Required for local dev
- `DATABASE_URL` - PostgreSQL connection string
- `REDIS_URL` - Redis for session storage
- `SENDGRID_API_KEY` - Transactional email
### Client-safe (NEXT_PUBLIC_ prefix)
- `NEXT_PUBLIC_STRIPE_PK` - Stripe publishable key
- `NEXT_PUBLIC_APP_URL` - Used for OG tags
### Never expose to client
- `STRIPE_SECRET_KEY`
- `SUPABASE_SERVICE_ROLE_KEY`
Load order: `.env.local` overrides `.env`
With this context, Claude Code will correctly scope variables when generating code, add appropriate server-only guards, and flag if it's about to write a secret to a client-accessible module. Related: see how this pairs with Next.js App Router setup on Claude Code for full-stack projects.
Checking your Claude Code usage before long automation runs
Environment variable management often comes up in the context of longer, automated tasks: seeding databases, running migration scripts, generating boilerplate across many files. These sessions consume usage quota quickly.
You can check your current usage with the /usage slash command inside Claude Code, or by visiting claude.ai/settings/usage. The issue is neither option gives you a live heads-up during a deep work session. By the time you think to check, you might already be mid-task when the 5-hour lockout hits.
Usagebar solves this by showing your remaining Claude Code quota in the macOS menu bar, with smart alerts at 50%, 75%, and 90% consumption. Your credentials are stored in macOS Keychain, never in plaintext. It's available on a pay-what-you-want model, including a free tier for students. If you're running token-heavy environment setup tasks, knowing you have 15% left before a reset is exactly the kind of signal that prevents a broken deploy mid-migration.
For more on tracking usage windows, see when does Claude Code usage reset and how to check Claude Code usage limits.
Get Usagebar - instant download, flexible pricing, free for students.
Key takeaways
- Claude Code inherits environment variables from the launching shell. Export them before running
claude. - Use
direnvor shell profiles for persistent, project-scoped variable loading. - Document required variables in
CLAUDE.mdso Claude understands your secrets structure and writes safer code. - Never paste secret values directly into Claude Code prompts. Use env vars and let Claude execute commands that consume them.
- Before long automation sessions, check your usage quota with
/usageor use Usagebar to get live menu bar alerts.
Sources
Never Get Locked Out Mid-Task Again
Never hit your usage limits unexpectedly. Usagebar lives in your menu bar and shows your 5-hour and weekly limits at a glance.
Get Usagebar$9 — one-time, lifetime updates