How to Secure Your OpenAI API Key
OpenAI keys are high-value targets. Here's how to keep them secure—backend only, rate limits, and quotas.
What this problem means
Your OpenAI API key unlocks paid API access. If it's in frontend code, it gets scraped within hours. If it's leaked, attackers rack up bills. Securing it means: backend only, rate limits, and per-user quotas.
Why this is dangerous
- Cost explosion: Leaked keys can generate $50K+ in bills in days.
- No built-in limits: OpenAI doesn't cap spend—you pay for what's used.
- Fast detection: Keys in frontend code are scraped within hours.
Real-world example
A startup embedded their OpenAI key in a React app for a chat feature. Within 48 hours, the key was scraped and used to generate $82,000 in API charges. The startup had no rate limits, no per-user quotas, and no alerts. They discovered the breach when the invoice arrived.
How to fix it
1. Backend only: All OpenAI calls must go through a backend. The frontend never touches the key.
2. Environment variables: Use `OPENAI_API_KEY` in server env only. Never use `NEXT_PUBLIC_` or any client-exposed env.
3. Rate limiting: Limit requests per user, per IP, or per API key.
4. Per-user quotas: Cap tokens or requests per user per day.
5. Billing alerts: Set up alerts in the OpenAI dashboard at 50%, 80%, and 100%.
Tools and configurations
- Backend proxy: Node.js, Python, or serverless functions.
- Environment variables: Server-only, never in client bundles.
- Redis: For distributed rate limiting.
- OpenAI dashboard: Usage and billing alerts.
Common mistakes
- Putting the key in frontend code.
- Using `NEXT_PUBLIC_` for the key.
- No per-user limits or quotas.
- No billing alerts.
Quick checklist
- [ ] Move all OpenAI calls to a backend proxy
- [ ] Use server-only environment variables
- [ ] Add rate limiting and per-user quotas
- [ ] Set up billing alerts in OpenAI dashboard
- [ ] Rotate any key that was ever in frontend code
Need help with production readiness? Get a free 30-minute audit.
Book Free 30-Min Production AuditCheck if your system has this risk
Take the 60-second production readiness assessment to identify gaps in your infrastructure.
Start AssessmentFrequently asked questions
- Can I use my OpenAI key in the frontend?
- No. Any key in frontend code can be extracted. Use a backend proxy for all OpenAI calls. The frontend calls your API; your server calls OpenAI.
- How do I set up OpenAI billing alerts?
- In the OpenAI dashboard, go to Settings > Billing. Set up usage limits and email alerts. You can also use AWS or a third-party tool to monitor spend.
- What if my OpenAI key was leaked?
- Rotate the key immediately in the OpenAI dashboard. Revoke the old key and create a new one. Move all API calls to a backend proxy so the key is never exposed again.