Protecting API Keys
Why API Keys Need Protection
API keys are essentially passwords that grant access to services and data. When exposed in client-side code, they can be easily extracted by anyone inspecting your website's source code.
Common API Key Exposure Issues
The most common ways developers accidentally expose API keys include:
- Hardcoding keys directly in JavaScript files
- Including keys in environment variables that are bundled with the client code
- Storing keys in public repositories
- Embedding keys in mobile app binaries
Best Practices for API Key Security
1. Never Include Keys in Frontend Code
API keys that need to access external services should never be included in code that gets sent to the browser. Instead, make the API calls from your server.
// DON'T DO THIS
const apiKey = "sk_live_1234567890abcdef";
fetch(`https://api.example.com/data?key=${apiKey}`);
2. Use Environment Variables Properly
When using environment variables with frameworks like Next.js, remember that variables prefixed with NEXT_PUBLIC_
will be included in the client bundle. Only use this prefix for non-sensitive information.
// Server-side only (.env)
API_SECRET_KEY=sk_live_1234567890abcdef
// Can be exposed to client (.env)
NEXT_PUBLIC_API_URL=https://api.example.com
3. Implement a Backend Proxy
Create backend endpoints that make the authenticated API requests for your frontend. This keeps sensitive keys secure on your server.
// Frontend code
fetch('/api/get-data') // Call your own backend
// Backend code (server-side only)
app.get('/api/get-data', (req, res) => {
// Use API key safely here
const apiKey = process.env.API_SECRET_KEY;
// Make request to third-party service
})
4. Use Token Expiration and Scope Limitation
When possible, use tokens with limited scope and short expiration times to minimize potential damage if they're compromised.
Monitoring for API Key Exposure
Regularly scan your codebase and public repositories for accidentally committed secrets using tools like:
- Git-secrets
- SecureVibing's API key detection
- GitHub secret scanning
What To Do If You've Exposed Keys
- Revoke and rotate the compromised keys immediately
- Check access logs for unauthorized use
- Remove the keys from your code history (though assume they've been compromised)
- Implement proper security controls before deploying new keys
Ready to secure your website?
Use our security scanner to check your site for vulnerabilities.