setup

>API Key Management

api-keysecurityenvironment

API keys are the secret sauce that connects your code to Claude's capabilities — but they're also your biggest security vulnerability if handled wrong. One misplaced API key in a public repository can lead to unauthorized usage charges and potential data breaches. The good news? Proper API key management is straightforward once you know the patterns.

You'll learn how to securely store your Anthropic API key using environment variables, set up different approaches for various development scenarios, and avoid the common pitfalls that trip up even experienced developers.

Why Environment Variables Matter

Hardcoding API keys directly in your source code is like leaving your house key under the doormat with a sign pointing to it. When you commit code with embedded secrets, those keys become visible to anyone with repository access — and they stay in your Git history even after you "fix" the problem.

Environment variables solve this by keeping sensitive data separate from your codebase. Your application reads the key at runtime from the system environment, while your source code remains clean and shareable.

Here's what NOT to do:

# ❌ Never do this!
client = anthropic.Anthropic(api_key="sk-ant-api03-...")

And here's the secure approach:

# ✅ This is the way
import os
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

Setting Up Environment Variables on Your System

The method for setting environment variables depends on your operating system and shell. Here's how to set them permanently for different environments.

macOS and Linux (Bash/Zsh)

Add the export command to your shell profile file. For most modern macOS systems, that's ~/.zshrc:

# Open your shell profile
echo 'export ANTHROPIC_API_KEY="sk-ant-your-key-here"' >> ~/.zshrc

# Reload your shell configuration
source ~/.zshrc

# Verify it's set
echo $ANTHROPIC_API_KEY

For Linux systems using Bash, use ~/.bashrc instead:

echo 'export ANTHROPIC_API_KEY="sk-ant-your-key-here"' >> ~/.bashrc
source ~/.bashrc

Windows

On Windows, you can set environment variables through the System Properties dialog or use PowerShell:

# Set for current session
$env:ANTHROPIC_API_KEY="sk-ant-your-key-here"

# Set permanently (requires admin privileges)
[Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-your-key-here", "User")

For Command Prompt:

# Set for current session
set ANTHROPIC_API_KEY=sk-ant-your-key-here

# Set permanently
setx ANTHROPIC_API_KEY "sk-ant-your-key-here"

Using .env Files for Project-Specific Configuration

While system-wide environment variables work well for personal development, projects often need more flexibility. That's where .env files shine — they let you set environment variables per project while keeping them out of version control.

Setting Up .env Files

First, create a .env file in your project root:

# Create the .env file
echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" >> .env

# CRITICAL: Add .env to .gitignore
echo ".env" >> .gitignore

# Verify .gitignore was updated
cat .gitignore

Loading .env Files in Your Code

Most languages have libraries to load .env files automatically. Here are examples for popular languages:

Python with python-dotenv:

import os
from dotenv import load_dotenv
import anthropic

# Load environment variables from .env file
load_dotenv()

# Now use the environment variable
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

Install the dependency first:

pip install python-dotenv

Node.js with dotenv:

require('dotenv').config();
const Anthropic = require('@anthropic-ai/sdk');

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

Install with npm:

npm install dotenv

Node.js with built-in support (Node 20+):

// No package needed for Node.js 20+
const Anthropic = require('@anthropic-ai/sdk');

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

Run with the --env-file flag:

node --env-file=.env your-script.js

Handling Multiple Environments

Real projects often need different API keys for development, testing, and production. Here's how to manage multiple environments cleanly.

Environment-Specific .env Files

Create separate files for each environment:

# Development
echo "ANTHROPIC_API_KEY=sk-ant-dev-key" >> .env.development

# Production  
echo "ANTHROPIC_API_KEY=sk-ant-prod-key" >> .env.production

# Add all to .gitignore
echo -e ".env*\n!.env.example" >> .gitignore

Create a template file that other developers can copy:

# .env.example (this gets committed)
ANTHROPIC_API_KEY=your-key-here

Loading the Right Environment

Most frameworks support environment-specific loading:

import os
from dotenv import load_dotenv

# Load based on environment
env = os.getenv('NODE_ENV', 'development')
load_dotenv(f'.env.{env}')

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

Common Pitfalls and How to Avoid Them

The .gitignore Gotcha

Adding .env to .gitignore after you've already committed it won't remove it from Git history. If you accidentally commit secrets:

# Remove from Git but keep local file
git rm --cached .env

# Add to .gitignore
echo ".env" >> .gitignore

# Commit the removal
git add .gitignore
git commit -m "Remove .env from tracking"

For already-pushed secrets, you'll need to rotate the API key immediately and consider using git filter-branch or BFG Repo-Cleaner to scrub the history.

Missing Environment Variables

Always handle missing environment variables gracefully:

import os

api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
    raise ValueError("ANTHROPIC_API_KEY environment variable is required")

client = anthropic.Anthropic(api_key=api_key)

Development vs Production Mix-ups

Use clear naming conventions and validation to prevent accidentally using production keys in development:

import os

api_key = os.environ["ANTHROPIC_API_KEY"] 
if os.getenv("NODE_ENV") == "production" and "dev" in api_key:
    raise ValueError("Cannot use development API key in production!")

Pro Tips for Better API Key Management

Use descriptive names for multiple keys: If you're working with multiple Anthropic projects, use prefixed environment variables like PROJECT_A_ANTHROPIC_API_KEY and PROJECT_B_ANTHROPIC_API_KEY.

Validate keys at startup: Add a simple API call during application initialization to verify your key works, rather than discovering authentication failures later.

Consider key rotation: Set calendar reminders to rotate API keys periodically, especially for production applications.

Use secrets management in production: For production deployments, consider dedicated secrets management services like AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault instead of plain environment variables.

What's Next

Now that your API keys are secure, you're ready to dive into Claude Code's capabilities. Consider exploring rate limiting and error handling patterns to build robust applications, or look into Claude Code's streaming responses for real-time interactions. The foundation you've built here will serve you well as your Claude-powered applications grow in complexity.