- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
How to Use API Keys in Any Web App — Guide & Best Practices
API keys let your application authenticate to third‑party services (maps, payments, data APIs). This post explains where to put them, how to keep them secret, and working code examples for both client & server.
1) What is an API key and why it matters
An API key is a short token (string) that identifies your application to an API provider. Providers use keys to track usage, apply rate limits, and restrict access. Because keys grant access, they must be kept secret when possible.
2) Never put secret keys in public client code
Important rule: Do not embed private API keys inside frontend JavaScript, HTML, or mobile apps. Anything shipped to users can be inspected (DevTools, network logs), and a leaked key can be abused.
If an API provider gives you two types of keys — public (safe for client) and secret (must stay on a server) — only use the public key in the browser.
3) Recommended architecture (client ⇄ server ⇄ external API)
Best pattern: your frontend calls your backend; your backend holds the secret key and calls the external API. This keeps secrets safe and lets you add caching, rate limiting, and logging.
4) Example: Node.js (Express) proxy — secure way
Server stores the key in environment variables and uses it when calling the external API. The frontend calls your server endpoint.
// server.js (Node + Express)
const express = require('express'); const fetch = require('node-fetch'); // or global fetch in newer Node require('dotenv').config(); const app = express(); const PORT = process.env.PORT || 3000;
app.get('/api/weather', async (req, res) => { const q = encodeURIComponent(req.query.q || 'London'); const key = process.env.WEATHER_API_KEY; // secret if (!key) return res.status(500).json({ error: 'Missing API key' }); const url = https://api.example.com/weather?q=${q}&apikey=${key}; const r = await fetch(url); const data = await r.json(); res.json(data); });
app.listen(PORT, () => console.log('Server listening', PORT));
`.env` (do not commit to git):
# .env
WEATHER_API_KEY=sk_live_XXXXXXXXXXXXXXXX
5) Minimal frontend that calls your backend
// script inside your web page
async function fetchWeather(city){ const res = await fetch(/api/weather?q=${encodeURIComponent(city)}); const json = await res.json(); console.log(json); }
6) If you must call third‑party API directly from the browser
Some providers offer restricted API keys for client use (domain restrictions, limited scopes). If allowed, do these:
- Restrict the key to your website origin (example.com)
- Limit allowed operations (read‑only whenever possible)
- Monitor usage and set alerts for spikes
// Example: client-side call (only with a public/restricted key)
const KEY = 'pk_live_public_example'; fetch(https://api.service.com/data?apikey=${KEY}) .then(r => r.json()) .then(console.log);
7) Security best practices (short checklist)
- Store secrets in environment variables or secret managers (AWS Secrets Manager, GCP Secret Manager).
- Do not commit keys to git — add them to `.gitignore`.
- Use a server-side proxy for secret keys.
- Apply minimal privileges and expiration to keys where supported.
- Set domain/IP restrictions on keys that are used in clients.
- Rotate keys regularly and revoke compromised keys immediately.
- Log and alert on abnormal usage spikes.
8) Handling rate limits & caching
On your server, cache responses where possible (short TTL) to reduce calls. Respect provider rate limits and implement exponential backoff on failures.
9) Debugging tips
- Check network calls in DevTools to ensure keys are not leaked in query strings or referer headers.
- Use mock/staging API keys in development.
- Run `git status` and `git log` to verify keys were never committed; use `git-secrets` or pre-commit hooks to scan for patterns.
10) Final practical example — Full HTML snippet for a site
This small page shows a frontend that talks to your server endpoint that holds the secret. Save the server example earlier and host it; then this page will request your server.
<!-- index.html (frontend) -->
Weather app
- Get link
- X
- Other Apps
Comments
Post a Comment