Exchange Rate API Key Security: Keep Your Key Out of the Browser
6 min read
If you are wondering whether you can call an exchange rate API straight from browser JavaScript, the short answer is: you can make the request, but you should not ship your API key to do it. Anything sent to the browser, including a key in a bundle, an environment variable inlined at build time or a header in a fetch call, is visible to every visitor through dev tools.
The fix is small. Keep the key on a server you control, expose one narrow endpoint to your frontend, and let the server talk to the rates API. This article explains what is actually at risk, shows a minimal proxy in Node.js, and covers what to do when a key leaks anyway.
Why an exchange rate API key in the browser is a problem
An API key is a credential tied to your account. For a rates API, a leaked key does not expose customer data, but it still costs you in three ways:
- Quota theft. Someone else's script can spend your monthly request units. When the quota runs out, your real checkout or dashboard starts getting
quota_exceedederrors. - Rate-limit starvation. Every plan has a per-second limit. Heavy traffic on a leaked key can push your legitimate calls into
rate_limit_exceeded(HTTP 429). - Unplanned upgrades. If you respond to the drain by moving to a bigger plan, you pay for traffic that was never yours.
"But it's only exchange rates" is a common objection. The data is not secret, but the key is. Think of it like a phone number you pay per call on: the content of the call is harmless, the bill is not.
Places keys leak without anyone noticing
Frontend bundles are the obvious one, but they are not the only one:
- Variables prefixed for the client in frameworks (for example, names that your build tool inlines into the bundle) are public by design.
- Mobile apps: strings inside an app package can be extracted.
- Public repositories and committed
.envfiles, including old commits you have since "deleted". - Screenshots, support tickets and pasted logs that include the
Authorizationheader. - CI logs that echo environment variables.
The pattern: a thin backend proxy
Instead of the browser calling the rates API, it calls your own endpoint. Your server adds the Authorization: ApiKey ... header and forwards the request. The authentication docs describe the header format.
A proxy gives you four things beyond hiding the key:
- An allowlist. Only the currencies your product uses can be requested, so nobody can use your endpoint as a free general-purpose rates service.
- Caching. Many visitors asking for USD to EUR within the same few seconds can share one upstream request.
- Input validation. Bad codes are rejected before they reach the API.
- A stable contract. Your frontend depends on your endpoint, not on upstream details.
A minimal Node.js proxy
This example uses Express and the built-in fetch in Node 18 or newer. The key comes from an environment variable and never reaches the client.
import express from "express";
const app = express();
const API_BASE = "https://api.getratesapi.com";
const API_KEY = process.env.GETRATESAPI_KEY;
// Only the codes your product actually needs.
const ALLOWED = new Set(["USD", "EUR", "GBP", "JPY", "BTC"]);
const TTL_MS = 30_000;
const cache = new Map(); // "EUR/USD" -> { at, body }
app.get("/api/rate/:base/:quote", async (req, res) => {
const base = req.params.base.toUpperCase();
const quote = req.params.quote.toUpperCase();
if (!ALLOWED.has(base) || !ALLOWED.has(quote)) {
return res.status(400).json({ code: "invalid_asset_symbol" });
}
const cacheKey = `${base}/${quote}`;
const hit = cache.get(cacheKey);
if (hit && Date.now() - hit.at < TTL_MS) {
return res.json(hit.body);
}
try {
const upstream = await fetch(`${API_BASE}/v1/rates/${base}/${quote}`, {
headers: { Authorization: `ApiKey ${API_KEY}` },
});
const body = await upstream.json();
if (!upstream.ok) {
// Pass on only the machine-readable code, not internals.
return res.status(upstream.status).json({ code: body.code });
}
cache.set(cacheKey, { at: Date.now(), body });
return res.json(body);
} catch {
return res.status(503).json({ code: "temporarily_unavailable" });
}
});
app.listen(3000);
Because the allowlist is finite, the cache can never grow beyond the number of allowed pairs. That is a quiet but useful property: an open-ended cache keyed on user input is its own denial-of-service risk.
The frontend then calls your endpoint, with no secrets involved:
const res = await fetch("/api/rate/EUR/USD");
const data = await res.json();
// data.rate is a string such as "1.0842" (an example value).
// Keep it as a string and let a decimal library do the math.
console.log(data.rate, data.status, data.as_of);
Note that the proxy passes through as_of and status. Your UI should still look at them; hiding the key must not hide freshness. See how to detect stale exchange rates for what to do when status is "stale".
Choosing a cache time in the proxy
The cache lifetime is a trade-off between request units and freshness. GetRatesAPI refreshes fiat currencies and metals every 60 seconds and crypto every 10 seconds, so caching fiat pairs for 30 seconds loses almost nothing, while caching a crypto pair for 30 seconds is three refresh cycles behind.
A reasonable starting point:
| Asset type | Upstream refresh | Sensible proxy TTL |
|---|---|---|
| Fiat and metals | 60 seconds | 30 to 60 seconds |
| Crypto | 10 seconds | 5 to 10 seconds |
If the rate is only for display, a longer TTL is fine. If a customer will be charged based on it, use the approach in locking an exchange rate at checkout instead of a loose cache. More on this trade-off is in how to cache exchange rates without showing stale prices.
Other places where the proxy rule applies
Server-rendered pages. If your framework fetches on the server (for example, in a server-side data loader), the key stays on the server and no separate proxy is needed. Just make sure the key is not serialized into the page props.
Mobile apps. Treat the app like a browser. Your own backend should hold the key and the app should call your backend.
Serverless functions. These work well as a proxy. Store the key in the platform's secret store, not in the repository.
AI agents. If an assistant needs rates, the key belongs in the MCP client configuration on the machine or service running the agent, not in a prompt. The MCP setup guide covers this.
Good key hygiene
- Read keys from environment variables or a secret manager. Never hard-code them. In shell examples,
export GETRATESAPI_KEY=...and reference$GETRATESAPI_KEY. - Use separate keys per environment. One for development, one for production. A leak in a test script then never touches production quota.
- Keep keys out of logs. Redact the
Authorizationheader in request logging. - Watch usage. The
GET /v1/account/usageendpoint returns the period, used, quota and remaining units. A sudden jump you cannot explain is the first sign of a leaked key. Details are in the usage and quotas docs. - Rate-limit your own endpoint. The proxy should not let one visitor consume the whole per-second budget. Standard middleware for per-IP limits is enough.
What to do if a key leaks
Act in this order:
- Create a new key in the dashboard.
- Deploy the new key to your servers.
- Revoke the old key.
- Check usage for the period of exposure.
- Remove the key from the repository history or at least treat it as burned. Deleting a file in a later commit does not erase the old one.
Because keys are created, rotated and revoked in the dashboard, you can do this in minutes without contacting anyone. Doing step 1 before step 3 avoids downtime. Practice the rotation once before you need it.
Try it with a key you keep private
Create a free key at the GetRatesAPI sign-up (no credit card), test pairs in the dashboard playground, then put the proxy above in front of your frontend. If your traffic grows, compare plans on the pricing page. The free plan's 500 units are enough to build and test the whole pattern.