← All Posts

Can I Setup Environment Variables with Claude Code? Yes, Here's How

Yes, you can set up environment variables with Claude Code. Claude Code inherits the environment from your shell session, and you can also use .env files, project-level CLAUDE.md configuration, and the claude --env flag. This applies to any developer using Claude Code on macOS or Linux who needs to pass API keys, secrets, or runtime config into their agentic workflows without hardcoding credentials.

  • Claude Code reads your shell environment variables automatically on launch
  • Project-scoped config in CLAUDE.md can document expected variables for teammates
  • Sensitive keys are never sent to Claude unless you explicitly reference them in a prompt

How Claude Code handles environment variables

Claude Code runs as a process in your terminal, which means it inherits your current shell environment. Any variable you've exported before launching Claude Code is available to the tools and scripts it runs on your behalf.

For example, if you run export DATABASE_URL=postgres://... before starting Claude Code, any shell command Claude executes during your session can access that variable. This is the simplest method and requires no extra configuration.

According to the Claude Code documentation on Pro and Max plans, Claude Code is designed to operate inside your existing developer environment, making shell-level environment variables the natural first-class mechanism for runtime configuration.

What are the main ways to set environment variables for Claude Code?

Method 1: Shell export (recommended for quick sessions)

The fastest approach for a single session:

export OPENAI_API_KEY="sk-..."
export DATABASE_URL="postgres://user:pass@host/db"
claude

These variables persist for the lifetime of your terminal session and are immediately available to any tool Claude Code invokes.

Method 2: .env file with a loader

For project-specific variables, use a .env file at the root of your project and load it before launching Claude Code:

# Load with direnv (recommended)
echo 'dotenv' >> .envrc
direnv allow

# Or source manually
set -a; source .env; set +a
claude

This approach pairs well with direnv, which automatically loads and unloads environment variables as you cd into and out of project directories. Make sure your .env file is listed in .gitignore before committing.

Method 3: Document required variables in CLAUDE.md

For team projects, add a section to your CLAUDE.md file that documents the environment variables your project expects. This gives Claude Code context about what variables are needed and lets it remind collaborators to set them up:

## Environment Setup

The following variables must be set before running Claude Code on this project:

- `DATABASE_URL` - PostgreSQL connection string
- `STRIPE_SECRET_KEY` - Stripe API secret key
- `REDIS_URL` - Redis connection URL for caching

Claude Code reads CLAUDE.md at the start of every session, so this doubles as onboarding documentation. For a deeper dive on this pattern, see the guide on env variable management on Claude Code.

Method 4: Pass variables inline for one-off commands

For a single invocation without polluting your shell environment:

DATABASE_URL="postgres://..." claude "run the migration script"

This is useful for CI pipelines or when you want strict isolation between different project contexts.

How to keep secrets secure when using Claude Code

Claude Code does not automatically send your environment variables to Claude's API. Variables are only transmitted if they appear in a prompt or if Claude reads a file that references them. Follow these practices to avoid accidental exposure:

  • Never paste raw secrets into the chat. Reference file paths or variable names instead (e.g., "use the value in $DATABASE_URL").
  • Add .env to your .gitignore before letting Claude Code make commits.
  • Use macOS Keychain for long-lived credentials. Tools like Usagebar also use macOS Keychain to securely store your Claude API credentials, so they never sit in plaintext config files.
  • Rotate keys after broad shell sessions if you're unsure what Claude accessed during a long agentic run.

If your project uses AWS, the guide on AWS S3 bucket setup on Claude Code covers how to pass AWS credentials safely through environment variables without hardcoding them in prompts.

Using environment variables in Claude Code hooks

If you've configured Claude Code hooks, your hook scripts also inherit the shell environment. This means you can use environment variables inside hook commands to conditionally run linters, formatters, or deployment scripts based on the current environment (e.g., NODE_ENV, CI).

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Write",
      "hooks": [{"type": "command", "command": "if [ \"$RUN_LINT\" = 'true' ]; then npm run lint; fi"}]
    }]
  }
}

SSH keys and environment variables together

Environment variables and SSH keys often go hand-in-hand when Claude Code is managing deployments or cloning private repos. The SSH key setup guide for Claude Code walks through pairing SSH agent forwarding with shell environment variables for seamless access to private infrastructure during agentic sessions.

What about Claude Code's /usage command and session context?

One underrated reason to get your environment variables right before starting Claude Code is that a misconfigured environment often causes tool failures mid-session. If Claude Code hits a wall because DATABASE_URL is missing, you may burn through a large portion of your usage window debugging something that could have been prevented.

You can check your current usage at any time with the /usage command inside Claude Code, or by visiting claude.ai/settings/usage. If you want persistent, at-a-glance visibility without switching windows, Usagebar sits in your macOS menu bar and shows your remaining usage with smart alerts at 50%, 75%, and 90% so you're never surprised by a lockout mid-task.

Usagebar is free for students and uses a pay-what-you-want model, so there's no reason not to have it running alongside your Claude Code sessions. Get Usagebar for an instant download and start tracking your usage without ever leaving your editor.

Key takeaways

  1. Claude Code inherits shell environment variables automatically. Export them before launching.
  2. Use a .env file with direnv or manual sourcing for project-scoped secrets.
  3. Document required variables in CLAUDE.md to keep teammates in sync.
  4. Never paste raw secrets into prompts. Reference variable names or file paths instead.
  5. Hook scripts also inherit the environment, enabling conditional automation based on runtime flags.
  6. Keep an eye on your usage window so a config issue mid-session doesn't cost you a 5-hour lockout.

Sources

Track Your Claude Code Usage

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