Skip to content
FR
  1. LuzineDebug
  2. AI & LLMs
  3. openai.AuthenticationError: Error code: 401 - In…
AI & LLMs Beginner ≈ 10 min to fix

Fix error 401 "Incorrect API key provided" / "invalid x-api-key"

Error message
openai.AuthenticationError: Error code: 401 - Incorrect API key provided: sk-proj-****abcd
  • anthropic.AuthenticationError: Error code: 401 - {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'invalid x-api-key'}}
  • openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable
  • You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth
  • 400 API key not valid. Please pass a valid API key. (API_KEY_INVALID)
In short

The API does not recognize the key it received: it is missing, mistyped, revoked or sent in the wrong header. Check that the environment variable holds the right key, test it with curl and regenerate it if needed. Never put an API key in front-end code.

Be the first to confirm this fix

What this error means

Every request to an LLM API must prove who it is. OpenAI expects the key in Authorization: Bearer, Anthropic in the x-api-key header, Gemini in x-goog-api-key. The server compares the key with the active keys of your organization or project. If it matches none, it returns HTTP 401 (invalid_api_key at OpenAI, authentication_error at Anthropic; Gemini returns a 400 API_KEY_INVALID). When no key is found at all, the SDKs fail before the call with a message asking you to set OPENAI_API_KEY or ANTHROPIC_API_KEY. The error is not about permissions (403) or quota (429): the key itself is rejected.

Common causes

  1. Key copied wrong: a missing character, a space, a trailing newline or quotes included in the .env file.
  2. Environment variable not loaded: .env never read, terminal not restarted after setx on Windows, or production server missing the variable.
  3. Old key takes precedence: a variable already exported in the shell wins, because python-dotenv does not override existing variables by default.
  4. Key revoked or project deleted: key rotation, key disabled after a detected leak, archived project or workspace.
  5. Wrong provider or wrong header: an OpenAI key sent to Anthropic, or an Anthropic key sent as Authorization: Bearer instead of x-api-key.

Step-by-step fix

  1. Check the variable without printing the key

    Check the length and prefix (sk-proj- for OpenAI, sk-ant- for Anthropic) without printing the full key in a terminal or shared logs.

    bash
    # macOS / Linux (bash, zsh)
    echo "${#OPENAI_API_KEY} ${OPENAI_API_KEY:0:8}"
    
    # Windows (PowerShell)
    $env:OPENAI_API_KEY.Length
    $env:OPENAI_API_KEY.Substring(0, 8)
  2. Test the key directly with curl

    A simple call to the models list isolates the problem: if curl also returns 401, the key is at fault, not your code.

    bash
    # OpenAI
    curl -s https://api.openai.com/v1/models \
      -H "Authorization: Bearer $OPENAI_API_KEY" | head -c 300
    
    # Anthropic
    curl -s https://api.anthropic.com/v1/models \
      -H "x-api-key: $ANTHROPIC_API_KEY" \
      -H "anthropic-version: 2023-06-01" | head -c 300
    
    # Gemini
    curl -s https://generativelanguage.googleapis.com/v1beta/models \
      -H "x-goog-api-key: $GEMINI_API_KEY" | head -c 300
  3. Store the key in an unversioned .env file

    One line per key, with no quotes or spaces around =. Add .env to .gitignore before the first commit.

    ini
    # .env
    OPENAI_API_KEY=sk-proj-your-key
    ANTHROPIC_API_KEY=sk-ant-your-key
  4. Load the .env and remove stale values

    In Python, load_dotenv() reads the file but does not replace a variable already set in the shell: remove the old one with unset (or pass override=True in development). In Node.js 20.6+, --env-file loads the file with no dependency.

    python
    # Python
    from dotenv import load_dotenv
    from openai import OpenAI
    
    load_dotenv()          # reads .env
    client = OpenAI()      # picks up OPENAI_API_KEY from the environment
    
    # shell: drop a stale exported key
    # unset OPENAI_API_KEY
    
    # Node.js 20.6+
    # node --env-file=.env server.js
  5. Regenerate the key if revoked or leaked

    Create a new key in the provider’s console (OpenAI Platform, Anthropic Console, Google AI Studio), update it everywhere (local, CI, hosting), then revoke the old one. If the key was published on GitHub or in a JavaScript bundle, treat it as compromised.

  6. Call the API from the server, never from the browser

    A key placed in front-end code (React, Vue, a mobile app) is visible to any visitor. Instead, expose a route on your back end that reads the key from the environment and calls the API on the client’s behalf.

    javascript
    // server.js - run with: node --env-file=.env server.js
    import express from "express";
    import Anthropic from "@anthropic-ai/sdk";
    
    const app = express();
    app.use(express.json());
    const client = new Anthropic(); // reads ANTHROPIC_API_KEY
    
    app.post("/api/chat", async (req, res) => {
      const msg = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages: [{ role: "user", content: String(req.body.message ?? "") }],
      });
      const text = msg.content
        .filter((b) => b.type === "text")
        .map((b) => b.text)
        .join("");
      res.json({ text });
    });
    
    app.listen(3000);

Did this fix work for you?

Confirm it in one click: it will rise for the next developers stuck on the same error.

Keep it from coming back

  • Keep keys only in environment variables or a secrets manager, never in the repository or in client code.
  • Turn on a secret scanner (GitHub secret scanning, gitleaks) to block commits that contain a key.
  • Use one key per project and per environment, so you can revoke one without breaking everything.

Frequently asked questions

My key worked yesterday, why a 401 today?

It was probably revoked: manual rotation, deleted project or automatic disabling after a public leak was detected. Check its status in the console and create a new one.

Can I put my OpenAI key in a VITE_ or NEXT_PUBLIC_ variable?

No. Those prefixes inject the value into the JavaScript sent to the browser, so the key becomes public. Call the API from a server route.

What is the difference between a 401 and a 403 error?

401 means the key is missing or invalid. 403 means the key is valid but has no access to the requested resource (model, project or region).

Useful tools for this error

More AI & LLMs errors

All AI & LLMs errors →