Web & App Development2026-07-275 min readStacks Horizon
The Golden Rule: Client vs. Server
The Golden Rule: Never put secret API keys in frontend code (React, Vue, mobile apps). Frontend code is public; use a backend proxy to attach the secret key before forwarding requests.
Why can't you just put an API key in your React or mobile app?
- Frontend code is public code. Anything shipped to a browser or compiled into an iOS/Android package can be inspected, reverse-engineered, or intercepted.
- The Backend Proxy Pattern: Instead of having the user's browser call an external API (like OpenAI, Stripe, or Twilio) directly, the frontend calls your API server. Your backend then attaches the secret key and forwards the request.
[ Frontend / Client ]
│
│ 1. Request (with user auth token)
▼
[ Your Backend Proxy ] ── 2. Request + Secret API Key ──► [ External Service ]
▲ │
│ │
└────────────────── 3. Response ───────────────────────────┘
1. Storing Keys Safely in Development
Never hardcode API keys into your source code repository (git).
Environment Variables
Store keys in environment variables outside your version control system:
- Create a
.envfile in your project root:
PORT=5000
THIRD_PARTY_API_KEY=sk_live_123456789abcdef
- Add
.envto your.gitignorefile immediately:
# .gitignore
.env
node_modules/
Accessing Env Variables in Code
- Node.js / Express: Use the
dotenvpackage.
import dotenv from 'dotenv';
dotenv.config();
const apiKey = process.env.THIRD_PARTY_API_KEY;
- Python / FastAPI or Flask: Use
python-dotenv.
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("THIRD_PARTY_API_KEY")
2. Production Key Management
In production, local .env files become difficult to manage across multiple servers or serverless functions.
- Environment Injectors: Host platforms like Vercel, Render, Heroku, or AWS Elastic Beanstalk allow you to inject environment variables directly through their dashboard or CLI.
- Dedicated Key Vaults: For high-security enterprise apps, store secrets in dedicated key vaults rather than standard environment variables:
- AWS Secrets Manager / Parameter Store
- HashiCorp Vault
- Azure Key Vault
- GCP Secret Manager
3. Building a Backend Proxy Endpoint
Here is a simple example using Node.js and Express showing how to proxy a request to a third-party service so your key stays safely hidden:
import express from 'express';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
app.use(express.json());
app.post('/api/generate-summary', async (req, res) => {
const { text } = req.body;
if (!text) {
return res.status(400).json({ error: 'Text prompt is required.' });
}
try {
// Calling external API securely from the backend
const response = await fetch('https://api.external service.com/v1/summarize', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.THIRD_PARTY_API_KEY}`
},
body: JSON.stringify({ text })
});
const data = await response.json();
res.status(response.status).json(data);
} catch (error) {
res.status(500).json({ error: 'Failed to communicate with external service.' });
}
});
app.listen(5000, () => console.log('Server running on port 5000'));
4. Key Security Checklist
| Action | Why It Matters |
|---|---|
| Apply IP & Domain Restrictions | Restrict your API keys at the provider level so they only work when called from your backend's IP address. |
| Implement Rate Limiting | Prevent abuse on your own endpoint (using tools like express-rate-limit or Redis) so malicious users don't spam your backend proxy. |
| Enable Key Rotation | Periodically rotate production keys. Good key vaults handle this automatically without downtime. |
| Use Automated Scanners | Tools like GitGuardian or GitHub Secret Scanning alert you instantly if a key is accidentally committed to a repository. |
What to Do If a Key Leaks
- Revoke Immediately: Go to the provider's dashboard and invalidate/delete the exposed key.
- Issue a New Key: Generate a new key and update your environment variables.
- Audit Usage Logs: Check the service logs to see if unauthorized requests or charges occurred while the key was exposed.
- Clean Git History: Merely deleting the file in a new commit doesn't remove it from your Git history—use tools like
BFG Repo-Cleanerorgit-filter-repoto scrub it completely.
Comments
Share your thoughts on this article.
Loading comments…
