LLM API error · 401
Invalid API key (401)
A 401 means the key was missing, malformed, revoked or from the wrong account. The causes in order of likelihood, and what to check first.
What it means
The provider could not authenticate the request. The key was absent, malformed, revoked, or belongs to a different organisation than the one the request targeted.
It is almost never a provider problem. In practice it is an environment variable that did not load, a key that was rotated, or whitespace.
Why it happens
Most likely cause first.
- 1
The environment variable did not load
The single most common cause. A .env file not read in the current environment, a variable set in one shell and used in another, or a deployment where the secret was never configured.
- 2
Whitespace or quotes in the key
A trailing newline from copy-paste, or quotes included when the value was pasted into a config UI that did not need them. The key looks correct in every log.
- 3
The key was rotated or revoked
Frequently because it leaked and somebody rotated it correctly. Check whether a rotation happened before assuming a bug.
- 4
Wrong organisation or project
Keys are scoped. A key valid for one project fails against another, and the error does not always make that obvious.
How to fix it
Print the length of the key, never the key
If the length is zero, it did not load. If it is one or two characters longer than expected, you have whitespace. Logging the value itself creates a new leak in your log store.
Trim it
Strip whitespace and surrounding quotes at the point of use. This costs one line and eliminates an entire category of this error.
Confirm the key is current and correctly scoped
Check it exists in the provider console, has not been revoked, and belongs to the organisation and project the request targets.
Check it never entered your codebase
If it did, rotate it and scan the text you have been sending to APIs. A key in a prompt is a key in somebody’s logs.
Secret Scanner for PromptsAPI keys, tokens, private keys and connection strings, found before you send.
Stopping it happening again
- Keys in a secret manager or environment variables, never in source control, never in client-side code, never in a prompt.
- Fail loudly at startup if the key is missing, rather than at the first user request.
- Scan anything you paste into a model for credentials — the most common leak is an engineer debugging a config file in a chat window.
Tools that help
Frequently asked questions
- Can I put my API key in frontend code if I restrict it?
- No. Anything in frontend code is public regardless of obfuscation, and provider keys do not support the kind of origin restriction that would make it safe. Proxy through your own backend.
- I rotated my key and it still fails. Why?
- Usually a cached environment: a running process holding the old value, a build-time variable baked into an artefact, or a deployment that has not restarted. Confirm the running process sees the new value.