Tutorial · JavaScript

Currency conversion in JavaScript

Fetch exchange rates on the server, convert and format amounts with Intl.NumberFormat, and keep your API key out of the browser.

Updated October 1, 2026 · 2 min read

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.

Frequently asked questions

Can I call a currency API directly from the browser?

Technically yes, but your API key would be visible to anyone. Call the API from your server (or a serverless function), cache the rates and send only the rates to the browser.

How do I format a currency amount in JavaScript?

new Intl.NumberFormat('en-US', { style: 'currency', currency: 'EUR' }).format(1234.5) returns '€1,234.50' and uses the right number of decimals for each currency.

Exchange rate API

Get these rates in your app

currencyapi delivers real-time and historical exchange rates for 170+ currencies, crypto and metals as JSON, updated as often as every 60 seconds.

300 free requests every month. No credit card required.

GET https://api.currencyapi.com/v3/latest?base_currency=USD&currencies=EUR,GBP,JPY

{
  "meta": { "last_updated_at": "2026-09-30T23:59:59Z" },
  "data": {
    "EUR": { "code": "EUR", "value": 0.8828 },
    "GBP": { "code": "GBP", "value": 0.7556 },
    "JPY": { "code": "JPY", "value": 157.98 }
  }
}

Keep reading

Start using our Currency API for free today!

Get 300 requests / month for free