Skip to content
PromptFable guideTool guide

Managing API Keys Locally

How to keep model API keys out of your code and repository: environment variables, a git-ignored .env file, why keys never belong in frontend bundles, what to do when a key leaks, and where secret managers fit in production.

For: Developers setting up an LLM API key on their own machine for the first time

Why API keys need careful handling

An API key works like a password: whoever holds it can use your account. For a model API, that means running requests billed to you and possibly reaching files or settings attached to your account. Keys leak in predictable ways: committed to a repository, embedded in a web page, pasted into a chat or printed in a log. The habits in this guide close each of those routes.

Use environment variables

An environment variable is a named value that the operating system hands to a program when it starts. Your code reads the key from the environment at run time, so the key is never written into a source file. Official SDKs usually look for a particular name automatically: Anthropic's quickstart uses ANTHROPIC_API_KEY, and Google's Gemini documentation recommends GEMINI_API_KEY. Check each provider's current quickstart, because details like these can change.

  1. Step 1: Set the variable for one terminal session

    This is fine for a quick test. The variable disappears when you close the terminal, and the command may be saved in your shell history, so prefer a .env file for regular work.

    Bash
    export GEMINI_API_KEY="paste-your-key-here"

    macOS or Linux (bash or zsh)

  2. Step 2: Or set it in Windows PowerShell

    PowerShell
    $env:GEMINI_API_KEY = "paste-your-key-here"

    Applies to the current PowerShell window only

  3. Step 3: Read it in your code and fail early if it is missing

    Python
    import os
    
    KEY_NAME = "GEMINI_API_KEY"  # or ANTHROPIC_API_KEY, depending on your provider
    
    api_key = os.environ.get(KEY_NAME)
    if not api_key:
        # Stop with a clear message instead of sending a request that will be rejected
        raise SystemExit(f"{KEY_NAME} is not set. See README.md for setup steps.")

    What you should see: Without the variable, the script stops at once with your message. With it set, the script carries on, and the key never appears in your code.

Keep local keys in a .env file that Git ignores

A .env file holds NAME=value lines in your project folder and is loaded when your program starts. It is convenient because it sits next to your code, and that is exactly what makes it risky: it must never be committed.

  1. Step 1: Add .env to .gitignore before you create the file

    Ignoring it first means there is never a moment when Git could pick it up.

    Text.gitignore
    # Local secrets: never commit
    .env
    .env.*
    !.env.example
    
    # Python virtual environment
    .venv/
  2. Step 2: Create the .env file with your keys

    Text.env
    ANTHROPIC_API_KEY=paste-your-key-here
    GEMINI_API_KEY=paste-your-key-here
  3. Step 3: Commit a .env.example instead

    It lists the variable names with no values, so a teammate knows what to set. The !.env.example line in .gitignore keeps this one file trackable.

    Text.env.example
    # Copy to .env and fill in your own values
    ANTHROPIC_API_KEY=
    GEMINI_API_KEY=
  4. Step 4: Load the file when your program starts

    Python does not read .env files by itself. A small library such as python-dotenv does it for you; install it inside your project's virtual environment.

    Python
    import os
    
    from dotenv import load_dotenv
    
    load_dotenv()  # copies values from .env into the environment; variables already set win
    api_key = os.environ["ANTHROPIC_API_KEY"]
  5. Step 5: Confirm that Git ignores the file

    Bash
    git check-ignore -v .env

    What you should see: Git prints the .gitignore rule that matches .env. If it prints nothing, the file is not ignored: fix that before you commit anything.

Never put keys in frontend code

Anything shipped to a browser or a mobile app can be read by its users. Build tools that insert environment variables into JavaScript bundles do not hide them; the key ends up in a file anyone can download. Frameworks that expose only variables with a special public prefix to the browser do this deliberately, so never give a secret that prefix.

Instead, the browser calls your own backend and the backend calls the model API. That also gives you one place to authenticate users, apply rate limits and validate requests before they cost you anything.

Where the key lives
  1. Browser or app

    Holds no key. Calls your own API.

  2. Your backend

    Checks the user, applies limits, reads the key from its environment.

  3. Model API

    Receives the key over HTTPS, from your server only.

If a key leaks

Treat a key as compromised as soon as it appears anywhere outside its intended environment: a repository, a chat, a ticket, a screenshot or a log. Deleting the message or the commit is not enough, because copies may already exist.

  1. Step 1: Revoke the key in the provider's console

    Do this first. It stops all further use at once.

  2. Step 2: Create a replacement and update every place that used the old key

    Local .env files, CI secrets and deployed services.

  3. Step 3: Check usage and billing

    Look for requests you did not make, and contact the provider's support if you find any.

  4. Step 4: Remove the key from where it leaked

    Delete the message or file. Removing a key from Git history needs a history-rewriting tool and a force push, and anyone who already cloned the repository keeps the old copy, which is why revoking comes first.

  5. Step 5: Fix the cause

    Add the missing ignore rule, a pre-commit secret scan or a log filter so the same leak cannot happen again.

Secret managers in production

A .env file is a convenience for one developer's machine. Shared and production environments need a secret manager: a service that stores secrets encrypted, controls who and what can read them, records access and supports rotation. Cloud platforms, CI systems and hosting providers each offer one.

  • Give each environment its own key. Development, staging and production should never share one.
  • Grant read access to the deployed service's identity rather than to individual people wherever you can.
  • Set an expiry or a rotation schedule where the provider supports it, and rotate when someone with access leaves the team.
  • Turn on the spending limits and usage alerts your model provider offers, so misuse of a leaked key is noticed quickly.

Whatever tools you use, the principle described in The Twelve-Factor App (opens in a new tab) holds: configuration that changes between deployments, including credentials, belongs in the environment, not in the code.

Written by
PromptFable Editorial
Last updated 13 Nov 2026
Review
Not yet reviewed
All developer resources

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.