API key authentication keeps the Codex CLI usable in headless environments, CI pipelines, and locked-down servers where browser-based sign-in is not practical. It is also useful when you need usage billed directly to an OpenAI Platform account instead of a ChatGPT subscription.
The Codex CLI reads an API key from standard input when you run codex login --with-api-key, then caches credentials for reuse across future runs. The CLI and IDE extension share the same cached credentials, so logging in once covers both clients.
API key usage is billed at standard API rates, and cached credentials live in either the OS credential store or /~/.codex/auth.json when file-based storage is enabled. Treat the key and cached credentials like passwords, and rotate or revoke them immediately if exposure is suspected.
Related: How to check Codex login status
Related: How to log out of Codex
Steps to log in to Codex with an API key:
- Copy the API key from the OpenAI dashboard.
https://platform.openai.com/api-keys
- Pipe the API key into codex login –with-api-key.
$ printenv OPENAI_API_KEY | codex login --with-api-key Logged in
Export OPENAI_API_KEY securely (CI secret, keychain, or a short-lived shell export) before running the command.
Credential storage is controlled by cli_auth_credentials_store (file, keyring, or auto).
- Verify the login state when authentication completes.
$ codex login status Logged in using API key
codex login status exits 0 when credentials are present, which is useful in automation.
- Run a simple command to confirm authenticated requests succeed.
$ codex exec "Return OK." OK
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
