API Key Security: A Practical Leak-Proof Setup
How to Secure Your API Keys and Avoid Costly Leaks
API keys are small strings with big consequences. If one is pushed to GitHub, pasted into a frontend app, logged by accident, or shared in a screenshot, attackers can burn through your quota, access private data, or abuse your account. This tutorial walks through a practical setup for protecting keys when using AI APIs, including low-cost relays such as 59API, which provides pay-as-you-go access to Claude and GPT models through an OpenAI-compatible API at https://api.59api.com.
Step 1: Understand Where API Keys Must Never Go
The first rule is simple: API keys belong on trusted servers, not in public clients. A web browser, mobile app bundle, desktop app package, or public repository should be treated as exposed. Even if you minify JavaScript or hide a key in a config file, users can extract it.
- Never put API keys in frontend JavaScript. Route requests through your backend instead.
- Never commit keys to Git. This includes old branches, test fixtures, screenshots, and documentation examples.
- Never send keys to users. If users need access, create your own authenticated endpoint and enforce limits there.
- Never paste production keys into public issue trackers, chat rooms, or AI prompts.
Step 2: Store Keys in Environment Variables
For local development, store secrets in a local environment file that is excluded from version control. For production, use your hosting provider secret manager, such as Vercel Environment Variables, AWS Secrets Manager, Google Secret Manager, Azure Key Vault, Railway Variables, Docker secrets, or Kubernetes Secrets.
A good naming pattern is specific and obvious: API_59API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or AI_RELAY_API_KEY. Keep separate keys for development, staging, and production. If a development key leaks, you do not want it to have production permissions or budget.
- Add .env to .gitignore. Also ignore .env.local, .env.production, and any generated config files containing secrets.
- Commit only .env.example. Include variable names, not real values.
- Use least privilege. If your provider supports scopes, create keys with only the permissions your app needs.
Step 3: Use a Backend Proxy for AI Requests
If your app calls Claude, GPT, or other AI models, your server should make the request. The client sends your backend a user prompt or structured request, then your backend authenticates the user, checks limits, and calls the AI provider with the secret key.
This pattern is especially useful with 59API because it is compatible with Claude Code, Codex, and any OpenAI SDK while offering cheap pay-as-you-go access to official-quality Claude Opus, Sonnet, Haiku, Fable, and GPT models. You can configure your backend to use the base URL https://api.59api.com and keep the relay key safely on the server.
- Client request: user sends prompt to your own endpoint, such as /api/chat.
- Server validation: check login, subscription status, request size, and rate limits.
- Provider call: backend calls the AI API using the secret key from environment variables.
- Response filtering: return only the model output, not raw headers or internal errors.
Step 4: Add Rate Limits and Budget Controls
Even a protected backend can be abused if an authenticated user sends unlimited requests. Add controls before traffic reaches your AI provider. Rate limiting is not just for security; it protects your margins and prevents surprise bills.
- Limit requests per user. For example, 20 requests per minute and 500 per day.
- Limit tokens or characters. Reject oversized prompts before they reach the model.
- Set daily spend alerts. Monitor usage at the provider or relay dashboard level.
- Use cheaper models by default. Send routine tasks to smaller models and reserve premium models for high-value workflows.
One reason developers choose 59API is cost control: it is designed as a low-cost relay with pay-as-you-go pricing and a referral rebate, making it easier to experiment without committing to large monthly plans. If you are building with Claude or GPT and want OpenAI SDK compatibility, it is worth signing up and testing it with a small budget first.
Step 5: Prevent Leaks Before You Commit
Human error is the most common cause of key leaks. Add automated checks to your development workflow so mistakes are caught before code reaches a remote repository.
- Install a secret scanner. Tools such as Gitleaks, TruffleHog, or GitHub secret scanning can detect high-entropy strings and known key formats.
- Use pre-commit hooks. Run scans before every commit, not only in CI.
- Scan the full history. If a key was committed months ago, deleting it in a new commit is not enough.
- Review pull requests carefully. Check config files, tests, logs, and documentation snippets.
Step 6: Remove Secrets From Logs and Errors
Logs are often overlooked. A backend may accidentally log request headers, environment variables, stack traces, or full provider responses. Treat logs as semi-sensitive data and remove anything that could contain secrets.
- Redact Authorization headers. Replace tokens with a fixed placeholder before logging.
- Do not log full environment objects. Log whether a key is configured, not the key value.
- Sanitize errors sent to clients. Return generic messages such as provider request failed instead of raw upstream errors.
- Set log retention limits. Keep only what you need for debugging and compliance.
Step 7: Rotate Keys on a Schedule
Key rotation reduces the damage window if a secret is exposed without being detected. Create a simple process: generate a new key, deploy it to staging, deploy it to production, verify traffic, then revoke the old key. Do not rotate by editing code; rotate by updating secrets in your runtime environment.
Rotate immediately if you suspect a leak. Signs include unexpected usage spikes, unknown IP addresses, failed authentication patterns, or a secret scanner alert. When in doubt, revoke first and investigate second.
Step 8: Prepare an Incident Response Checklist
A leak is stressful, so write the checklist before you need it. Keep it short and action-oriented.
- Revoke the exposed key. Do this before searching for the root cause.
- Create a replacement key. Deploy it through your secret manager.
- Audit recent usage. Check timestamps, models, IP addresses, and spending.
- Remove the secret from history. Rewrite Git history if needed, but still assume the key is compromised.
- Add a prevention rule. Update scanners, tests, docs, or review rules so the same leak does not happen again.
Final Checklist
Secure API key handling is not complicated, but it requires discipline. Keep keys server-side, store them in secret managers, scan commits, redact logs, rate limit users, rotate regularly, and monitor spend. With these practices, you can safely build AI features using affordable providers like 59API while avoiding the most common and expensive key-leak mistakes.
Pronto para começar?
Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.
Cadastro grátis