Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Currency API in JavaScript and Node.js: Fetch, Cache, Convert and Format Correctly

Calling a currency API from JavaScript takes one line. Doing it without leaking your key, hammering the API or showing "€1,234.5600001" takes a bit more. This post builds a small, correct setup on Node.js 18+ (built-in f

Calling a currency API from JavaScript takes one line. Doing it without leaking your key, hammering the API or showing "€1,234.5600001" takes a bit more. This post builds a small, correct setup on Node.js 18+ (built-in fetch) with AllRatesToday's API.

You need a free API key (no card).

1. A cached client (Node)

// fx.js
const KEY = process.env.ALLRATES_KEY;
const TTL_MS = 5 * 60 * 1000;           // rates update every 60 s; 5 min is plenty for display
const cache = new Map();                 // base -> { at, rates }

export async function getRates(base = "USD", targets = ["EUR", "GBP", "JPY", "INR"]) {
  const key = `${base}:${targets.join(",")}`;
  const hit = cache.get(key);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.rates;

  const url = new URL("https://allratestoday.com/api/v1/rates");
  url.searchParams.set("source", base);
  url.searchParams.set("target", targets.join(","));

  const res = await fetch(url, { headers: { Authorization: `Bearer ${KEY}` } });
  if (!res.ok) {
    if (hit) return hit.rates;           // serve the last good rates rather than fail
    throw new Error(`FX API ${res.status}: ${(await res.json()).error}`);
  }
  const rates = Object.fromEntries((await res.json()).map((q) => [q.target, q.rate]));
  cache.set(key, { at: Date.now(), rates });
  return rates;
}

One request returns every target you list, and it counts as a single call.

2. Keep the key on the server (Express)

Anything in browser JavaScript is public. Put a small endpoint in front of the API:

// server.js
import express from "express";
import { getRates } from "./fx.js";

const app = express();

app.get("/api/rates", async (req, res) => {
  const base = String(req.query.base || "USD").toUpperCase();
  if (!/^[A-Z]{3}$/.test(base)) return res.status(400).json({ error: "bad base" });
  try {
    res.set("Cache-Control", "public, max-age=300");
    res.json(await getRates(base));
  } catch (e) {
    res.status(502).json({ error: "rates unavailable" });
  }
});

app.listen(3000);

The browser calls /api/rates?base=EUR. Your key never leaves the server, and every visitor shares the same cached rates.

3. Convert money without float bugs

0.1 + 0.2 !== 0.3 applies to money too. Work in minor units (cents, pence, yen), as integers:

const MINOR = { JPY: 0, KRW: 0, KWD: 3, BHD: 3 };       // default 2
const digits = (ccy) => MINOR[ccy] ?? 2;

export function convertMinor(amountMinor, from, to, rate) {
  const major = amountMinor / 10 ** digits(from);
  return Math.round(major * rate * 10 ** digits(to));   // integer minor units of `to`
}

convertMinor(12_999, "USD", "JPY", 159.323274);          // $129.99 -> 20710 (yen)

Round once, at the end. Rounding at each intermediate step is where cents go missing.

4. Format for humans

const fmt = (minor, ccy, locale = "en-US") =>
  new Intl.NumberFormat(locale, { style: "currency", currency: ccy })
    .format(minor / 10 ** digits(ccy));

fmt(20710, "JPY");             // "¥20,710"
fmt(11887, "EUR", "de-DE");    // "118,87 €"

Intl.NumberFormat handles symbols, separators and decimal places for every currency, in every locale. Don't build currency strings by hand.

5. Which currencies exist?

const res = await fetch("https://allratestoday.com/api/v1/symbols", {
  headers: { Authorization: `Bearer ${process.env.ALLRATES_KEY}` },
});

This returns 160+ ISO codes with names, useful for populating a currency picker once at build time.

Official rates for invoices

For prices on screen, the live mid-market rate is right. For invoices that have to follow a tax rule, use the central bank rate the rule names. It's on the same key:

const r = await fetch(
  "https://allratestoday.com/api/v1/central-bank/ecb/latest?source=EUR&target=USD",
  { headers: { Authorization: `Bearer ${process.env.ALLRATES_KEY}` } }
);
const { rate, rate_date } = await r.json();     // store rate_date with the invoice

Links

Rates by AllRatesToday.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.