Skip to content

How to Secure AI API Keys

Key idea:

AI API keys leak in 2026: (1) in client-side JS (main issue), (2) in GitHub public repos (secret scanning catches $20k+ monthly), (3) logs + error messages. Defence: (A) ALWAYS proxy via backend, (B) Budget limits + per-user rate limiting, (C) Auto-rotate keys quarterly, (D) Monitor cost anomalies via GCP/AWS alerts. Leak = $10k+ cloud GPU bill in 24 hours.

Below: step-by-step, working examples, common pitfalls, FAQ.

Try it now — free →

Step-by-Step Setup

  1. Never use API key in client-side JS / mobile app
  2. Backend proxy endpoint: POST /api/ai/chat → forwards to OpenAI
  3. Env vars: OPENAI_API_KEY in .env (600 permissions, not in git)
  4. Rate limit per user + per-IP (Redis sliding window)
  5. Budget alert: OpenAI Usage limits, GCP billing alert
  6. Key rotation: quarterly + after every incident
  7. Monitor for anomalies: spike in usage → auto-disable

Working Examples

ScenarioConfig
Backend proxy (Node/Express)app.post('/api/ai/chat', authMiddleware, async (req, res) => { const { message } = req.body; if (!rateLimiter.allow(req.user.id)) return res.status(429).json({ error: 'rate limit' }); const response = await openai.chat.completions.create({ model: 'gpt-5', messages: [{ role: 'user', content: message }] }); res.json({ text: response.choices[0].message.content }); });
Redis rate limitconst count = await redis.incr(`ai:${userId}:${hour}`); if (count === 1) await redis.expire(`ai:${userId}:${hour}`, 3600); if (count > 100) throw new Error('Rate limit exceeded');
OpenAI budget limits# In OpenAI Dashboard: # Settings → Billing → Usage limits # Hard limit: $100/month # Soft limit: $50/month (email alert)
GitHub secret scanning# Enable: Settings → Security → Secret scanning # GitHub auto-detects OpenAI/Anthropic keys # Push blocked if secret found
Key rotation cron# Quarterly rotation: # 1. Generate new key in OpenAI dashboard # 2. Update OPENAI_API_KEY in env # 3. Reload app # 4. Revoke old key after 24h

Common Pitfalls

  • Client-side JS key = instant leak (Network tab or decompile). NEVER
  • GitHub: even private repo if the wrong contributor is invited
  • Logs: console.log(process.env) may reach error tracker (Sentry, Datadog)
  • Mobile apps: reverse-engineering APK trivially finds keys in strings
  • Serverless env vars — safe, but deploy logs may contain them
HeadersCSP, HSTS, X-Frame-Options, etc.
SSL/TLSEncryption and certificate
ConfigurationServer settings and leaks
Grade A-FOverall security score

Why teams trust us

OWASP
guidelines
15+
security headers
<2s
result
A–F
security grade

How it works

1

Enter site URL

2

Security headers analyzed

3

Get grade A–F

What Does the Security Analysis Check?

The tool checks HTTP security headers, SSL/TLS configuration, server info leaks, and protection against common attacks (XSS, clickjacking, MIME sniffing). A grade fromA to F shows overall security level.

Header Analysis

Checking Content-Security-Policy, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and more.

SSL Check

TLS version, certificate expiry, chain of trust, HSTS support.

Leak Detection

Finding exposed server versions, debug modes, open configs, and directories.

Report with Recommendations

Detailed report explaining each issue with specific steps to fix it.

Who uses this

Security teams

HTTP header audit

DevOps

config verification

Developers

CSP & HSTS setup

Auditors

compliance checks

Common Mistakes

Missing Content-Security-PolicyCSP is the primary XSS defense. Without it, script injection is much easier.
Missing HSTS headerWithout HSTS, HTTPS-to-HTTP downgrade attacks are possible. Enable Strict-Transport-Security.
Server header exposes versionServer: Apache/2.4.52 helps attackers find exploits. Hide the version.
X-Frame-Options not setSite can be embedded in iframe for clickjacking. Set DENY or SAMEORIGIN.
Missing X-Content-Type-OptionsWithout nosniff, browsers may misinterpret file types (MIME sniffing).

Best Practices

Start with basic headersMinimum: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy. Takes 5 minutes.
Implement CSP graduallyStart with Content-Security-Policy-Report-Only, monitor violations, then enforce.
Hide server headersRemove Server, X-Powered-By, X-AspNet-Version from responses.
Configure Permissions-PolicyRestrict camera, microphone, geolocation access — only what is actually used.
Check after every deploySecurity headers can be overwritten during server configuration updates.

Get more with a free account

Security check history and HTTP security header monitoring.

Sign up free

Learn more

Frequently Asked Questions

What if key leaked?

Immediately: (1) Revoke key in dashboard, (2) Check usage for last 24h, (3) Rotate all related keys, (4) Review logs for suspicious calls, (5) Contact support if cost > $1k.

Is $10k leak cost real?

Yes. Automated bots scan GitHub + Shodan and instantly find new keys. 1 H100 GPU-hour = $2-5. 1000 parallel calls × 24h × $5 = $120k. Known cases.

Does proxy add latency?

Yes, +50-100ms. Mitigate: deploy proxy in the same region as the OpenAI endpoint. Streaming response keeps UX smooth.

How does Enterno secure keys?

All external API keys (OpenAI, Anthropic, Telegram) are in backend .env with 600 permissions. Proxy endpoints with rate limiting + user auth. See <a href="/en/security">Enterno Security Scanner</a>.