DEV Community

Zac
Zac

Posted on

Environment variables and Claude Code: the right setup

Environment variables and secrets are one of the areas where Claude Code needs explicit guidance. Here's how to set it up right.

The problem without guidance

Without instructions, Claude sometimes hardcodes values that should be environment variables. It knows not to hardcode passwords, but it might hardcode API endpoints, feature flags, or configuration values that belong in env.

Add to CLAUDE.md: "Never hardcode configuration values. Use environment variables for API endpoints, API keys, feature flags, database URLs, and any value that differs between environments."

.env files and Claude's access

Claude Code can read your .env file if you don't .claudeignore it. This means:

  • Claude can see your actual secrets (useful for understanding what's available)
  • You should never commit your .env file (you already knew this)
  • Add .env to .claudeignore if you don't want Claude reading it

The .env.example pattern

Keep a .env.example checked into your repo with all the variable names but no real values. Tell Claude in CLAUDE.md: "Reference .env.example for the list of available environment variables. Never read .env directly."

This gives Claude the context it needs (what variables exist) without exposing the values.

Generated code that uses env correctly

With the right setup, Claude will generate code like:

import os

API_URL = os.getenv('API_URL', 'http://localhost:8000')
if not API_URL:
    raise ValueError('API_URL environment variable is required')
Enter fullscreen mode Exit fullscreen mode

Rather than:

API_URL = 'https://api.myservice.com'  # Don't do this
Enter fullscreen mode Exit fullscreen mode

The commit-check pattern

Run a pre-commit check that scans for common secret patterns: API key formats, hardcoded URLs containing credentials, AWS key patterns. This catches the cases where Claude (or you) hardcoded something accidentally.

Top comments (0)