Guide
Convert Currency in JavaScript with fetch
Convert currency in JavaScript and TypeScript with fetch and an exchange rate API: typed responses, error handling, cross rates and safe key storage.
Updated
Converting money in JavaScript takes two things: a current exchange rate and a little care with rounding and display. This guide uses the built-in fetch of Node 18 and later, no client library, against the FXbase exchange rate API. Every request shown here is in the API reference, and the same code works in Deno, Bun and serverless functions.
Your first conversion
Create a free key in the console. Keys start with centy_live_. Put the key in an environment variable, here FXBASE_API_KEY, and try the convert endpoint from a terminal before you write any code:
curl "https://api.fxbase.dev/v1/convert?from=USD&to=EUR&amount=100" \
-H "Authorization: Bearer $FXBASE_API_KEY"The answer is JSON:
{
"from": "USD",
"to": "EUR",
"amount": 100,
"rate": 0.91126,
"result": 91.126,
"date": "2026-11-18",
"timestamp": "2026-11-18T16:00:04Z",
"source": "daily",
"tier": "developer"
}rate is units of to per one from, and result is amount times rate. date is the UTC day the rate belongs to and timestamp is when it was fetched. source tells you which feed answered: daily, hourly or live. It follows your plan, and falls back to another feed when the usual one has nothing fresh. Show the date next to any converted price, so nobody mistakes yesterday's rate for this minute's.
Convert currency with fetch in Node
The same request in Node is a few lines. URLSearchParams encodes the query, and the key goes in the Authorization header, never in the URL, where it would end up in logs:
// Runs on your server. The key never reaches a browser.
const API = "https://api.fxbase.dev";
const KEY = process.env.FXBASE_API_KEY;
export async function convert(from, to, amount) {
const query = new URLSearchParams({ from, to, amount: String(amount) });
const res = await fetch(`${API}/v1/convert?${query}`, {
headers: { Authorization: `Bearer ${KEY}` },
});
const body = await res.json();
if (!res.ok) {
// Errors are application/problem+json: branch on body.code.
throw new Error(`${body.status} ${body.code}: ${body.detail} (${body.requestId})`);
}
return body;
}
const quote = await convert("USD", "EUR", 100);
console.log(quote.result, quote.rate, quote.date, quote.source);Read the body once, then check res.ok. On success you get the conversion. On failure the body is an RFC 9457 problem document with a stable code, a human detail and a requestId to quote to support. Throwing all three makes a failed request easy to trace from your logs.
Currency codes are three upper-case letters. An unknown code such as XYZ is a 400 with unknown_currency; a malformed one, such as usd, or an amount of zero, is a 400 with invalid_request and a fields list naming each bad input. amount must be above 0 and at most one quadrillion.
Add TypeScript types
In TypeScript, describe the two shapes you get back, the conversion and the problem, and wrap fetch in one small helper. The types below match the fields in the API reference:
const API = "https://api.fxbase.dev";
export interface Conversion {
from: string;
to: string;
amount: number;
rate: number; // units of `to` per one `from`
result: number; // amount × rate
date: string; // the rates' UTC day, YYYY-MM-DD
timestamp: string; // when the rates were fetched, ISO 8601
source: "live" | "hourly" | "daily";
tier: string; // your plan
}
export interface Problem {
type: string;
title: string;
status: number;
detail: string;
code: string; // stable: branch on this
requestId: string; // quote it to support
fields?: string[]; // invalid inputs, for invalid_request
}
export class FxbaseError extends Error {
constructor(readonly problem: Problem) {
super(`${problem.code}: ${problem.detail}`);
}
}
export async function get<T>(path: string, params: Record<string, string>): Promise<T> {
const res = await fetch(`${API}${path}?${new URLSearchParams(params)}`, {
headers: { Authorization: `Bearer ${process.env.FXBASE_API_KEY}` },
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new FxbaseError((await res.json()) as Problem);
return (await res.json()) as T;
}
const quote = await get<Conversion>("/v1/convert", { from: "GBP", to: "JPY", amount: "250" });AbortSignal.timeout gives every call a deadline, so a slow network cannot hang a request handler. A typed error class lets callers branch on err.problem.code without parsing strings. Every field is listed under the convert endpoint, and the host every call uses is under base URL. An official TypeScript SDK is on the way Coming soon; until then, plain fetch is all you need.
Many conversions from one request
Calling /v1/convert for every amount on a page wastes requests. If you show a price in ten currencies, fetch the latest rates once and multiply locally. symbols narrows the answer to the codes you need, up to 200 of them:
// One call for every currency you show, then convert locally.
const latest = await get("/v1/latest", { base: "USD", symbols: "EUR,GBP,INR,JPY" });
// USD to anything: multiply by the rate.
const toInr = (usd) => usd * latest.rates.INR;
// Between two non-base currencies: a cross rate through the base.
const eurToGbp = (eur) => eur * (latest.rates.GBP / latest.rates.EUR);
console.log(latest.base, latest.date, toInr(25), eurToGbp(40));Rates are quoted per one unit of base. To convert between two currencies that are not the base, go through it: divide the target's rate by the source's. When you only need one pair, /v1/convert saves you the arithmetic and returns the rate it used.
Each answer can be reused for five minutes (Cache-Control: private, max-age=300), and every request, including a revalidation that comes back 304, counts toward your monthly quota. The currency converter guide shows a cache that keeps your request count flat however busy the page gets.
Round and format for display
Keep the full-precision number for arithmetic and round only when you display it. Intl.NumberFormat knows each currency's symbol and its number of minor units, so you do not have to:
const money = (amount, currency, locale = "en-US") =>
new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount);
money(quote.result, quote.to); // "€91.13"
money(1234.5, "JPY", "ja-JP"); // "¥1,235": JPY has no minor unitIf you store converted amounts, for an invoice or a ledger, store the rate, the date and the timestamp with them. You can then reproduce the number later and explain it, even after the rate has moved.
Converting in the browser
Your API key is a secret: anyone who has it can spend your quota. The API does not accept cross-origin calls from browsers, so a front end calls a route on your own server, and that route calls FXbase with the key:
// Your server exposes /api/convert and calls convert() from above.
const res = await fetch("/api/convert?" + new URLSearchParams({ from: "USD", to: "EUR", amount: "100" }));
const { result } = await res.json();Your route is also the right place to validate input, cache answers and apply your own limits per user. A key can also carry scope, IP address or referrer rules; a call that breaks them gets a 403 with forbidden. See authentication for the details.
Which plan you need
Conversion and latest rates work on every plan. The free Developer plan gives you 500 requests a month at up to 5 a minute, with daily rates, previous day, which is enough to build and test. Startup ($12 a month) moves to hourly rate snapshots and 30,000 requests; Growth ($49 a month) gives live rates, updated every 60 s and 250,000 requests. When you go over a limit you get a 429; the rate limits guide shows how to handle it.
Need past rates, for reports or backfills? The historical rates guide covers /v1/historical and /v1/timeseries.
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.