How to keep your Claude API key safe in a .env file

Day 2, 25 minutes · beginner

Goal of this lessonStore your Claude API key in an environment variable and a .env file that git ignores, and know what to do if it leaks.

Why it matters

An API key in your code is a key under the doormat. The moment the file lands in git, on GitHub or in a chat with a colleague, anyone who reads it can spend your credits. It happens to careful people too: one quick test with the key pasted in, one commit, and it is out.

There is a simple habit that prevents this: the key lives in one place outside your code, and your code reads it from there. Today you set that up for Linde's project at Harbour Lane Tea Co. At the end you have a project folder that git will never leak the key from, a tiny script that proves your code can find the key without showing it, and a plan for the day a key leaks anyway.

Environment variables: the key next to your code, not in it

An environment variable is a named value that your terminal hands to every program it starts. Your script asks for the value by name and never contains the value itself.

The Claude SDKs look for one name: ANTHROPIC_API_KEY. An SDK (software development kit) is a ready-made library that handles the calls to the API for you; Anthropic makes official ones for Python, TypeScript and five other languages. When ANTHROPIC_API_KEY is set, the SDK uses it by itself, and your code does not mention the key at all.

You can set the variable in your terminal, but then it is gone when you close it. A common way to keep it per project is a .env file: a plain text file in the project folder with one line per variable. The Python SDK docs suggest the python-dotenv package for this, so the key is not stored in source control. Node.js can read the same file with its --env-file option.

The .gitignore comes first

A .env file is only safe if git ignores it. A .gitignore file lists files and folders git should leave alone. Write it before you create .env, so there is never a moment where git could pick the key up. Then check with git status: that command lists the files git sees, and .env must not be among them.

The key docs say it plainly: keep keys out of source control, out of code that runs in a browser, and out of prompts. Two of those are worth spelling out:

  • Never in browser code. Anyone who opens a web page can read the code in it. If you ever build a website with Claude in it, your server calls the API, never the visitor's browser.
  • Never in a prompt. Do not paste the key into a chat with any AI tool, including Claude, to ask why a script fails. Share the error message instead.

And one rule for your own scripts: never print the key. Today's check script prints only whether it found a key and how long it is.

When a key leaks anyway

A short plan, built on the Developer API keys page:

  1. Stop the key. On the API keys page of the Console you can Disable a key, which you can undo with Re-enable, or Delete it, which is permanent. If you are not sure whether the key leaked, disable first.
  2. Make a new key and put it in your .env file.
  3. Check your usage in the Console for requests you did not make.

The docs also advise rotating keys on a schedule, which means replacing them with new ones from time to time. The expiry date you picked yesterday does that for you: when the key expires, requests with it fail with a 401 error and you make a new one.

The steps

  1. Make the project folder with a virtual environment and the two packages.
  2. Write .gitignore before anything secret exists.
  3. Create .env with your key from the password manager.
  4. Run the check script and see that it finds a key without printing it.
  5. Start git and confirm that .env is not in the list.
  6. Know where the Disable button is, before you need it.

Follow the steps below. There is a Python path and a Node path; pick one and keep it for the rest of the course.

Common mistakes

  • Spaces or quotes in the wrong place in .env. Write ANTHROPIC_API_KEY= directly followed by the key.
  • Creating .env in another folder. It must sit next to your script.
  • Adding .gitignore after the first commit. Git then already tracks .env, and ignoring it later does not remove it from history. If that happened, disable the key and make a new one.

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. On macOS or Linux: open a terminal and run these lines one at a time. They make the project folder, a virtual environment (a private Python install for this project) and install the SDK and python-dotenv.
    mkdir harbour-lane-replies
    cd harbour-lane-replies
    python3 -m venv .venv
    source .venv/bin/activate
    pip install anthropic python-dotenv
  2. On Windows: open PowerShell and run these lines one at a time instead.
    mkdir harbour-lane-replies
    cd harbour-lane-replies
    python -m venv .venv
    .venv\Scripts\Activate.ps1
    pip install anthropic python-dotenv
  3. In your code editor, create a file named .gitignore in the folder with these two lines and save it. Do this before the .env file exists.
    .env
    .venv/
  4. Create a file named .env with this one line. Replace sk-ant-... with your key from the password manager, keep no spaces around the = sign, and save.
    ANTHROPIC_API_KEY=sk-ant-...
  5. Create check_key.py with this code and run python check_key.py. It says whether the key was found, without ever printing it.
    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    
    key = os.environ.get("ANTHROPIC_API_KEY")
    if key:
        print("Key found. It is", len(key), "characters long.")
    else:
        print("No key found. Check your .env file.")
  6. Run git init and then git status. The list of files may show .gitignore and check_key.py, but never .env or .venv. If .env shows up, fix .gitignore first.
    git init
    git status
  7. For Node instead of Python: run npm init -y, npm pkg set type=module and npm install @anthropic-ai/sdk, add node_modules/ to .gitignore, save this as check_key.mjs and run node --env-file=.env check_key.mjs.
    const key = process.env.ANTHROPIC_API_KEY;
    if (key) {
      console.log(`Key found. It is ${key.length} characters long.`);
    } else {
      console.log("No key found. Check your .env file.");
    }
  8. If a key ever leaks, open the API keys page in the Console. Click Disable to stop it for now (you can turn it back on with Re-enable) or Delete to stop it for good. Then make a new key and put it in .env.

Note: The docs also show setx ANTHROPIC_API_KEY in PowerShell to set the key for every new terminal on Windows; then open a new terminal. If PowerShell refuses to run Activate.ps1, run your scripts with .venv\Scripts\python instead of python. The Node SDK needs Node.js 20 LTS or later. If Node says it does not know the --env-file option, install a newer Node.js.

Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.

Checked on 4 December 2026 · Source: Claude API docs: Developer API keys (opens in a new tab)

Create a free account to save your progress. Sign in or sign up