API keys are the credentials that give your application access to AI services. A leaked or mismanaged API key can result in unauthorized usage, unexpected costs, and potential data exposure. This guide covers the security practices every developer should follow when working with AI API keys.
Never Commit API Keys to Version Control
The single most common API key mistake is committing a key to a Git repository. Even if you immediately remove the key in a subsequent commit, the key is still visible in the repository history. Automated bots scan GitHub, GitLab, and Bitbucket repositories for exposed credentials and begin using them within minutes of exposure.
Use a .env.local or .env file for local development and add these files to .gitignore before your first commit. Check your .gitignore file before pushing:
# .gitignore
.env
.env.local
.env.*.localIf you have already accidentally committed a key, revoke it immediately from your API provider dashboard and generate a new one. Do not just delete it from the file.
Use Environment Variables in Production
For production deployments, use your hosting platform's secrets management:
- **Vercel**: Project Settings → Environment Variables
- **Railway**: Variables tab in your project settings
- **AWS**: Parameter Store or Secrets Manager
- **Docker**: Docker Secrets or environment injection at runtime
Never hardcode API keys in your application source code, configuration files, or Docker images. These can be extracted by anyone with access to your build artifacts.
Separate Keys by Environment
Use different API keys for development, staging, and production. This practice limits blast radius if one key is compromised — a leaked development key cannot be used to drain your production quota.
Most AI API platforms allow you to create multiple keys per account. Name them clearly:
daymora-dev-2026-05
daymora-staging-2026-05
daymora-production-2026-05Including the year and month in the key name makes it easier to enforce rotation schedules.
Proxy API Calls Through Your Server
Never send AI API keys from the browser. Client-side JavaScript is accessible to any user who opens your application — exposing keys in frontend code is equivalent to making them public.
Always proxy AI API calls through a server-side endpoint in your application. In Next.js:
// src/app/api/ai/route.ts — runs server-side only
export async function POST(req: Request) {
const response = await fetch("https://api.yourprovider.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.AI_API_KEY}`,
"Content-Type": "application/json",
},
body: await req.text(),
});
return response;
}The process.env.AI_API_KEY is never sent to the browser — it is only used in the server-side runtime.
Implement Rate Limiting
Even with server-side proxying, your application can be abused by users who make an excessive number of requests. Add rate limiting to your AI API proxy route to cap the number of requests per user per time window.
A simple in-memory rate limiter for development:
const rateLimits = new Map<string, { count: number; resetAt: number }>();
function checkRateLimit(userId: string, limit = 20, windowMs = 60000): boolean {
const now = Date.now();
const record = rateLimits.get(userId);
if (!record || record.resetAt < now) {
rateLimits.set(userId, { count: 1, resetAt: now + windowMs });
return true;
}
if (record.count >= limit) return false;
record.count++;
return true;
}For production, use a distributed rate limiter backed by Redis (e.g., @upstash/ratelimit) so limits work across multiple server instances.
Rotate Keys Regularly
Establish a key rotation schedule — every 90 days is a reasonable baseline for production keys. Rotation reduces the window of exposure if a key is compromised without your knowledge.
When rotating:
1. Generate the new key in your API provider dashboard
2. Add the new key to your deployment environment
3. Deploy the updated configuration
4. Verify the new key is working in production
5. Revoke the old key
Automated rotation using infrastructure tools like Terraform or AWS Secrets Manager can eliminate manual rotation steps.
Monitor for Unusual Usage
Set up usage alerts in your API provider dashboard to notify you when spending or request volume exceeds expected thresholds. An alert at 150% of your normal monthly usage gives you early warning of potential key abuse.
Review your API access logs regularly. Look for unusual patterns: requests from unexpected IP ranges, spikes in request volume at odd hours, or usage of models you did not intend to use.
What to Do If a Key Is Compromised
If you believe a key has been exposed:
1. Revoke it immediately from your API provider dashboard — do not wait
2. Audit your usage logs for unauthorized requests
3. Check your billing for unexpected charges
4. Generate a new key and deploy it
5. Review how the key was exposed to prevent recurrence
Speed matters in key compromise situations. Revoke first, investigate second.
Summary
Secure API key management is not complex but requires discipline. Keep keys out of version control, proxy all AI calls through your server, use separate keys per environment, and rotate regularly. These practices protect your application, your budget, and your users.