Fetch rates in Node.js (18+)
// rates.js — runs on the server
const API_KEY = process.env.CURRENCYAPI_KEY;
let cache = { at: 0, rates: null };
export async function getRates(base = "USD") {
if (cache.rates && Date.now() - cache.at < 10 * 60 * 1000) return cache.rates;
const url = `https://api.currencyapi.com/v3/latest?base_currency=${base}`;
const res = await fetch(url, { headers: { apikey: API_KEY } });
if (!res.ok) throw new Error(`currencyapi ${res.status}`);
const { data } = await res.json();
const rates = Object.fromEntries(Object.entries(data).map(([code, item]) => [code, item.value]));
cache = { at: Date.now(), rates };
return rates;
}
Convert between any two currencies
With USD-based rates you can convert between any pair:
export function convert(amount, from, to, rates) {
// rates are units of each currency per 1 USD
return (amount / rates[from]) * rates[to];
}
Format the result
const eur = convert(199.99, "USD", "EUR", await getRates());
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(eur);
// "176,56 €"
Intl.NumberFormat knows the symbol and the decimals of every currency (0 for JPY, 3 for KWD).
Expose rates to the browser
// Express
app.get("/api/rates", async (req, res) => {
res.set("Cache-Control", "public, max-age=600");
res.json(await getRates("USD"));
});
The browser fetches /api/rates and converts locally; your API key never leaves the server.
No code needed?
Embed the free currency converter widget with one line of HTML.