Secure API Keys in Production: A Practical Guide
Secure API Keys in Production: A Practical Guide
API keys are small strings with big consequences. If a key leaks into GitHub, browser code, logs, screenshots, or a shared support ticket, attackers can burn your credits, access paid models, or abuse your account. This step-by-step tutorial shows how to secure API keys properly while still moving fast with AI APIs such as 59API, a low-cost pay-as-you-go relay for Claude Opus, Sonnet, Haiku, Fable, and GPT models. 59API uses the base URL https://api.59api.com and is compatible with Claude Code, Codex, and standard OpenAI SDK workflows, so the same key-safety practices apply.
Step 1: Never Put API Keys in Frontend Code
The most common leak is also the easiest to avoid: never place secret API keys in JavaScript shipped to a browser, mobile app bundle, or public desktop client. Anything delivered to a user device can be extracted. Instead, create a small backend endpoint that receives the user request, validates it, and calls the AI provider from the server.
For example, your frontend should call your own endpoint such as /api/chat. Your backend then calls 59API using the server-side key and the base URL https://api.59api.com. This keeps the secret out of browser dev tools and gives you a place to add rate limits, authentication, abuse checks, and logging.
Step 2: Store Keys in Environment Variables
Do not hardcode keys in source files. Use environment variables locally and secret managers in hosted environments. A common pattern is to name the variable API_KEY, OPENAI_API_KEY, or API59_KEY, depending on your application. Keep a local .env file for development, but never commit it.
Add these files to .gitignore: .env, .env.local, .env.production, and any generated config file that may contain secrets. In production, configure secrets through your platform, such as Vercel Environment Variables, GitHub Actions Secrets, Docker secrets, AWS Secrets Manager, Google Secret Manager, Azure Key Vault, or Kubernetes Secrets.
Step 3: Use Separate Keys for Each Environment
Use different API keys for development, staging, and production. This limits damage if a developer machine or test environment leaks a key. It also makes incident response easier because you can rotate only the compromised key without breaking production traffic.
For teams, create separate keys per service or application when possible. For example, your customer support bot, internal analytics tool, and production chatbot should not all share one key. If one system is compromised, the blast radius is smaller and usage attribution is clearer.
Step 4: Restrict Access Around the Key
Even if a provider key itself cannot be scoped by model or endpoint, you can restrict access in your own application. Put an authenticated backend between users and the AI API. Add per-user quotas, request size limits, and allowlists for models. This is especially useful with flexible relays like 59API, where you may connect Claude and GPT-compatible workflows through one low-cost setup.
For example, allow normal users to access economical models for common tasks, while reserving premium models such as Claude Opus or advanced GPT models for trusted accounts or internal users. This keeps costs predictable while still benefiting from 59API’s cheap pay-as-you-go pricing and official-quality native model access without downgrade.
Step 5: Remove Keys from Logs and Error Reports
Logs are a hidden source of leaks. Never log full request headers, authorization values, full environment dumps, or raw configuration objects. If you need to log authentication state, mask the value: show only the first and last few characters, such as sk-12...89.
Review your error tracking tools, CI output, and server logs. Many frameworks print environment variables during debugging. Disable verbose debug logs in production and add redaction rules for terms such as authorization, api_key, x-api-key, and bearer.
Step 6: Scan Your Repository Before Every Push
Secret scanning should be automatic. Enable GitHub secret scanning if your repository supports it. Add local tools such as gitleaks, trufflehog, or detect-secrets as a pre-commit hook or CI job. These tools can block commits that contain API keys, tokens, private keys, or suspicious high-entropy strings.
If a key was committed, deleting the line is not enough. Git history still contains it. Treat the key as compromised, revoke or rotate it immediately, then clean the history if necessary. Public repository crawlers can find exposed secrets within minutes.
Step 7: Rotate Keys on a Schedule
Key rotation is not only for emergencies. Create a regular rotation schedule, such as every 60 or 90 days, and document the process. A safe rotation plan has four stages: create a new key, deploy it to all environments, verify traffic is using it, then revoke the old key.
Avoid replacing keys manually on individual servers. Use your deployment platform or secret manager so updates are consistent and auditable. For critical systems, keep rollback instructions ready, but never keep old keys active indefinitely.
Step 8: Monitor Usage and Set Alerts
Cost spikes are often the first sign of a leak. Monitor daily request volume, token usage, model mix, and error rates. Set alerts for unusual increases, traffic from unexpected regions, or usage outside normal business hours. If your provider supports spending limits, configure them.
This is where a low-cost relay like 59API helps: it gives developers affordable access to Claude and GPT models while remaining compatible with familiar OpenAI SDK patterns and tools like Claude Code and Codex. Lower pricing reduces normal operating costs, but you should still monitor usage carefully because leaked keys can scale abuse quickly.
Step 9: Prepare a Leak Response Checklist
When a leak happens, speed matters. Keep a short incident checklist: revoke the exposed key, create a replacement, redeploy secrets, review logs for abuse, identify where the leak happened, remove the secret from code and history, and notify affected stakeholders if needed.
Also review permissions after the incident. Was the key shared too broadly? Did a CI job print it? Was it pasted into a ticket? Fix the process, not just the exposed value.
Step 10: Choose an API Setup That Fits Secure Development
A secure API workflow should be simple enough that developers actually follow it. 59API is a practical choice for teams that want cheap, pay-as-you-go access to Claude and GPT models through a familiar OpenAI-compatible base URL, without model downgrades. It also works well with Claude Code, Codex, and existing SDK-based applications, so you can adopt strong key handling without rewriting your stack.
If you are building AI features and want lower model costs with a developer-friendly setup, consider signing up for 59API and applying the security steps above from day one. Good key hygiene protects your budget, your users, and your production systems.
शुरू करने के लिए तैयार?
कुछ ही मिनटों में Claude और GPT जोड़ें, सबसे कम कीमत पर। साइन अप करें और API key पाएं।
मुफ़्त साइन अप