Guide
How to Build a Currency Converter
Build a currency converter with an exchange rate API: a currency picker, a server-side rate cache with ETag and If-None-Match, cross rates and formatting.
Updated
A currency converter looks like a form with two dropdowns, but a good one gets three things right: it never exposes the API key, it does not spend a request on every keystroke, and it tells people how fresh the rate is. This guide builds one in six steps with Node and plain browser JavaScript, on top of the FXbase exchange rate API, which covers 166 currencies. The calls are all in the API reference.
Step 1: Put the key behind your own route
Anyone who holds your key can spend your quota, and the API does not accept cross-origin browser calls in any case. So the converter has two halves: a server that holds the key in an environment variable and talks to FXbase, and a page that talks only to that server. Create the key in the console; it starts with centy_live_. The authentication section shows how it is sent: an Authorization: Bearer header on every request.
The server below needs nothing beyond Node 18 or later. Any framework, such as Express, Fastify, Next.js route handlers or a serverless function, works the same way.
Step 2: Fill the currency pickers
GET /v1/currencies returns every supported ISO 4217 code. It returns codes only, so name them with the browser's or Node's own Intl.DisplayNames, which also localizes the names for free. This uses the small get() helper from the JavaScript guide:
const names = new Intl.DisplayNames(["en"], { type: "currency" });
const { currencies } = await get("/v1/currencies", {});
const options = currencies.map((code) => ({ code, name: names.of(code) ?? code }));
// [{ code: "AUD", name: "Australian Dollar" }, ...]The list changes rarely; its version field changes when it does. Fetch it when your server starts, or at build time, rather than on every page view.
Step 3: Fetch and cache the latest rates
One latest rates answer holds every currency against a base, which is all a converter needs. Every successful answer carries two headers that make caching easy, described under caching: Cache-Control: private, max-age=300, meaning you may reuse it for five minutes, and an ETag. After that, send the ETag back as If-None-Match: if the rates have not changed you get a 304 with no body, and you keep using what you have.
const API = "https://api.fxbase.dev";
const KEY = process.env.FXBASE_API_KEY;
const cache = new Map(); // base -> { body, etag, freshUntil }
// Daily rates (the Developer plan) change once a day: hold them longer than five minutes.
const MIN_TTL_SECONDS = Number(process.env.RATES_MIN_TTL_SECONDS ?? 300);
export async function latestRates(base = "USD") {
const hit = cache.get(base);
if (hit && Date.now() < hit.freshUntil) return hit.body;
const headers = { Authorization: `Bearer ${KEY}` };
if (hit?.etag) headers["If-None-Match"] = hit.etag;
const res = await fetch(`${API}/v1/latest?${new URLSearchParams({ base })}`, { headers });
// Cache-Control is "private, max-age=300": reuse an answer for five minutes.
const maxAge = Number(/max-age=(\d+)/.exec(res.headers.get("Cache-Control") ?? "")?.[1] ?? 0);
const freshUntil = Date.now() + Math.max(maxAge, MIN_TTL_SECONDS) * 1000;
if (res.status === 304) {
hit.freshUntil = freshUntil;
return hit.body; // unchanged: no body was sent
}
const body = await res.json();
if (!res.ok) {
if (hit) return hit.body; // serve the last good rates through an outage
throw new Error(`${body.code}: ${body.detail}`);
}
cache.set(base, { body, etag: res.headers.get("ETag"), freshUntil });
return body;
}The cache also keeps the converter working through a short outage: if FXbase answers with an error, the last good rates are served instead.
Pick the refresh interval with your quota in mind, because every request counts, including a 304: the ETag saves bandwidth, not requests. Refreshing one base every five minutes is about 8,640 requests a month, well inside Startup's 30,000 but far over the 500 of the free Developer plan. Its rates are daily, so on Developer set RATES_MIN_TTL_SECONDS to two hours (7200), about 360 requests a month.
Step 4: Serve the rates to the page
Expose one route that returns the cached rates. Validate the input before it reaches the API, so a typo is a cheap local 404 instead of a request against your quota:
import { createServer } from "node:http";
import { latestRates } from "./rates.mjs";
const CODE = /^[A-Z]{3}$/;
createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const base = url.searchParams.get("base") ?? "USD";
if (url.pathname !== "/api/rates" || !CODE.test(base)) {
res.writeHead(404).end();
return;
}
try {
const { date, timestamp, source, rates } = await latestRates(base);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ base, date, timestamp, source, rates }));
} catch {
res.writeHead(502).end();
}
}).listen(3000);However many people use the converter, FXbase sees at most one request per base currency per refresh interval. If the page lets people choose a base, keep one cache entry per base, as latestRates does, or always fetch one base and convert through it in the page, as the next step does.
Step 5: Convert and format in the page
Rates are units of each code per one unit of base, and the base itself is not in the list. To convert between any two currencies, go through the base: multiply by the target's rate and divide by the source's. Then format with Intl.NumberFormat, which rounds to each currency's minor units:
const { base, rates, date, source } = await (await fetch("/api/rates?base=USD")).json();
// Any pair through the base: from -> base -> to.
function convert(amount, from, to) {
const perBase = (code) => (code === base ? 1 : rates[code]);
return amount * (perBase(to) / perBase(from));
}
const fmt = (n, currency) =>
new Intl.NumberFormat(undefined, { style: "currency", currency }).format(n);
// amountInput, fromSelect, toSelect, output and asOf are elements of your form.
const to = toSelect.value;
output.textContent = fmt(convert(Number(amountInput.value), fromSelect.value, to), to);
asOf.textContent = `Rates for ${date} (${source})`;Converting in the page makes every keystroke instant and free. If you only ever need a single pair and would rather not do the arithmetic, the convert endpoint takes from, to and amount and returns the rate and the result; call it from the server, and cache it like the latest rates:
curl "https://api.fxbase.dev/v1/convert?from=EUR&to=INR&amount=49.99" \
-H "Authorization: Bearer $FXBASE_API_KEY"Step 6: Show how fresh the rate is
People trust a converter more when it says where the number comes from. Every answer has a date, the UTC day of the rates, a timestamp of when they were fetched, and a source: daily on the Developer plan, and usually hourly on Startup and live on Growth, falling back to another feed when that one has nothing fresh. Show them next to the result, as the last line of the page code does.
Finally, label the result as indicative. Banks and card networks add their own margin, so the rate a customer is charged can differ from a market rate. If the converter feeds real prices, store the rate and date you used with each order. When you are ready to go live, the rate limits guide shows how to handle a 429 gracefully.
Try it with a free key
The Developer plan is free and includes latest rates and conversion. Every request in this guide is in the API reference. Get a free API key.