OpenAI API Key Invalid or Revoked — Fix It Fast
The 'invalid API key' error occurs when OpenAI's API cannot authenticate your request due to a missing, revoked, expired, or incorrectly formatted key. This error is commonly seen by developers integrating the OpenAI API into applications or scripts. Resolving it typically takes just a few minutes by verifying or regenerating your credentials.
Why does this error happen?
How to fix it
Generate a New API Key
Log in to platform.openai.com and navigate to the API Keys section under your account settings. Click 'Create new secret key', give it a recognizable name, and copy it immediately — OpenAI will not display the full key again after this step.
Remove Leading and Trailing Spaces
When pasting an API key into a .env file or configuration panel, invisible whitespace characters can be accidentally included. Open your environment file and ensure the key value starts directly with 'sk-' and has no spaces or newline characters before or after it.
Verify Your Organization ID
If your account belongs to multiple OpenAI organizations, requests must include the correct Organization ID in the 'OpenAI-Organization' header. Find your Organization ID at platform.openai.com/account/org-settings and confirm it matches what is set in your application configuration.
Confirm Active Billing on Your Account
Navigate to platform.openai.com/account/billing and confirm that a valid payment method is on file and your usage limits have not been exceeded. Accounts with failed payments or exhausted free-tier credits may have API access suspended, which invalidates otherwise correct keys.
Code example
// Correct way to pass API key using the official Node.js SDK
// Store your key in an environment variable — never hardcode it
const OpenAI = require('openai');
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY, // e.g. sk-...
// organization: process.env.OPENAI_ORG_ID, // optional, if using multiple orgs
});
async function main() {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }],
});
console.log(response.choices[0].message.content);
}
main();Pro tip
Store your API key exclusively in environment variables or a secrets manager such as AWS Secrets Manager or HashiCorp Vault — never commit it to source control. Rotate your keys every 90 days and set up usage alerts in the OpenAI dashboard to catch unauthorized use before it leads to revocation.