Menu

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

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

DEV Community: javascript·allratestoday·5 days ago
#qtijuLBZ
#devtojavascript#devto#dev#const#rates
Long article (913 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.