Codex CLI picks up OPENAI_API_KEY from project .env (via shell auto-loading), causing 401 “AK/SK” errors and confusing /status

Resolved 💬 6 comments Opened Aug 15, 2025 by ac1982 Closed Nov 2, 2025

What version of Codex is running?

0.21.0

Which model were you using?

gpt-5

What platform is your computer?

Darwin 24.6.0 arm64 arm

What steps can reproduce the bug?

What steps can reproduce the bug?

  1. In any project folder, create a .env file containing:

``ini
OPENAI_API_KEY=sk-<some-other-key>
``

(Many shells/IDEs auto-load .env automatically — e.g., direnv, zsh-dotenv, VS Code terminal.)

  1. From that project directory, run:

``bash
codex --login # choose “Sign in with ChatGPT”
codex
``

  1. Ask Codex to perform any action (e.g., pls run npm lint, and if problems, try to fix them.).

What is the expected behavior?

What is the expected behavior?

  • When signed in via ChatGPT, Codex should use the token generated by that login, not silently override it with OPENAI_API_KEY from the local environment.
  • /status should display which credential is actually being used (ChatGPT token or environment key) and clearly indicate when an override is happening.

What do you see instead?

Additional information

  • Actual result: 401 Unauthorized errors such as:

``
AuthenticationError: the API key or AK/SK in the request is missing or invalid
``

even though /status still shows:

``
Provider: OpenAI
Model: gpt-5
Signed in with ChatGPT (Plan: Plus)
``

  • Removing or renaming OPENAI_API_KEY in .env immediately resolves the problem.
  • Workarounds:

``bash
env -u OPENAI_API_KEY codex
``

or rename the variable to something like APP_OPENAI_API_KEY.

  • Suggestions:
  • Add /status transparency for credential source.
  • Warn when environment variables override ChatGPT sign-in.
  • Provide a --ignore-env flag.

Additional information

_No response_

View original on GitHub ↗

This issue has 6 comments on GitHub. Read the full discussion on GitHub ↗