Skip to main content
API Key Setup10 min readPublished: 2026-03-31Updated: 2026-08-07

How to Create and Safely Use an OpenAI API Key (2026)

A practical walkthrough for creating an OpenAI API key, setting permissions, and avoiding common security mistakes.

By Heizi· Founder & Editor· Published: 2026-03-31· Updated: 2026-08-07Hands-on tested

1) Create the key in the official dashboard

OpenAI keys are created in the API Keys page of the developer platform at platform.openai.com. Use your organization account instead of personal throwaway accounts when this key is for production. If you haven't registered yet, the OpenAI API key tutorial walks through account creation, phone verification, and billing setup step by step.

After creation, store the secret immediately in a secure vault. Do not paste it into chat tools, tickets, or public docs. The key string starts with 'sk-' and is typically 51 characters long — if yours looks shorter or truncated, you may have copied it incompletely.

Give each key a descriptive name that reflects its purpose and environment, such as 'prod-backend-audit' or 'dev-staging-test'. This makes it much easier to identify which key to rotate or revoke when team members change roles or leave the organization. OpenAI's dashboard also lets you assign keys to specific projects, which helps with spending tracking and access isolation.

2) Set least-privilege permissions

OpenAI supports key-level permission modes such as All, Restricted, and Read Only. For production apps, prefer Restricted and enable only the endpoints your service actually needs — for example, enable 'Chat Completions' and 'Embeddings' if your app only does text generation and search. The full OpenAI API reference explains each permission scope in detail.

If multiple internal services use OpenAI, create separate keys per service. This limits blast radius and makes auditing easier.

A common mistake is creating a single key with All permissions and sharing it across multiple services. If one service is compromised, the attacker gains full access to your account — including the ability to delete models, change billing, or drain your credits. With Restricted keys, even a leaked key only exposes the specific endpoints it was scoped to, dramatically reducing the potential damage.

3) Use server-side secrets only

Never expose OPENAI_API_KEY in frontend JavaScript. Keep it in server environment variables and call OpenAI from your backend. If you accidentally expose the key in client-side code, revoke it immediately in the dashboard and create a new one — assume any exposed key is already compromised.

Use separate keys for development, staging, and production. Rotate keys periodically and immediately after team offboarding or suspected leakage.

Here's how to configure the key in a .env file and load it in a Node.js application:

For Next.js specifically, do NOT prefix your environment variable with NEXT_PUBLIC_. Variables prefixed with NEXT_PUBLIC_ are bundled into client-side JavaScript and will be visible to anyone who inspects your website's source code. A plain OPENAI_API_KEY variable is only accessible in Server Components and API routes, which is exactly what you want. Monitoring your usage also helps you catch unexpected cost spikes — understanding API costs early prevents surprises at the end of the month.

  • Store keys in env vars or a secret manager
  • Never commit keys to Git
  • Rotate keys on a schedule
bash
# .env file
OPENAI_API_KEY=sk-your-key-here

# .gitignore — make sure .env is listed
.env

Environment variable configuration for OpenAI API key

javascript
// Load the key from environment in Node.js
require('dotenv').config();

const { OpenAI } = require('openai');

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY, // never hardcode
});

Loading the API key from environment variables in Node.js

4) Validate with a minimal request

Before integrating business logic, send a minimal test call with your server key. This confirms that network policy, project settings, and permissions are all correct. If the test fails, you'll know the issue is with authentication or configuration — not your application code.

Log request IDs and response status codes for troubleshooting. Add alerting for repeated 401 and 429 errors. For a comprehensive guide to diagnosing these errors — including distinguishing rate limits from quota exhaustion and implementing safe retry strategies — see troubleshooting 401 and 429 errors.

A common pitfall during first-time setup is using the wrong base URL. The API endpoint is https://api.openai.com/v1 — not the ChatGPT URL. Another frequent issue is forgetting that free trial credits may have expired, resulting in a 429 'quota exceeded' error even though the key itself is valid.

5) Add operational guardrails

Set project budgets and monitor usage so quota issues are detected early. If your workload spikes, review rate-limit guidance and add retry with exponential backoff.

Treat key management as part of production readiness, not a one-time setup step. Schedule quarterly key rotations, review access logs for unusual patterns, and maintain a runbook for incident response so your team knows exactly what to do when a key is compromised.

Consider implementing a key management service if you have more than a handful of keys. Tools like AWS Secrets Manager, HashiCorp Vault, or Doppler can automate rotation, audit access, and integrate with your CI/CD pipeline — so a new deployment automatically picks up the latest key without manual intervention.

FAQ

Should I use one OpenAI key for all services?

It is safer to use separate keys per service or environment. Isolation makes incident response and auditing much easier.

Can I put OPENAI_API_KEY in client-side code?

No. Client-side exposure can leak your key and allow unauthorized usage.

What should I do after a suspected key leak?

Immediately rotate the key, audit recent usage, and tighten permissions before restoring traffic.

Related Providers

Sources