TutorialsCode

How to get live gold prices in Node.js

Call the goldprice.dev API from Node.js with native fetch, decimal.js, retry-on-429, and a 60-second TTL cache.

5 Jul 2026 · 3 min read

To get live gold prices in Node.js, send a GET to api.goldprice.dev/v1/spot/XAU-USD-SPOT with your API key in the X-API-Key header using native fetch, no HTTP library needed. Cache the response in a Map for 60 seconds and use decimal.js for price math. The free tier covers 5,000 calls/month, no credit card. Tested July 2026 against Node 22 LTS.

Get your goldprice.dev API key

Sign up for a free account at goldprice.dev/onboarding. After email confirmation, your dashboard shows a key starting with ga_live_. Set it as an environment variable:

Shell
export GOLDPRICE_API_KEY=ga_live_replace_with_your_key_here

The free tier includes 5,000 calls/month and gold spot in 31 currencies. No credit card required.

Install decimal.js

Node 18+ ships native fetch, so no HTTP client is needed. The one dependency is decimal.js, so price math stays exact instead of drifting on JavaScript's Number type. Install it:

shell
npm install decimal.js

Write the goldprice client

Save this as goldprice.mjs. The spot() function caches per symbol for 60 seconds in a Map, retries up to 3 times on 429 with exponential backoff, and returns prices as Decimal. Gold and silver quotes carry a single price, so bid and ask become null.

goldprice.mjs
// node: goldprice.mjs// curl-equivalent: https://api.goldprice.dev/v1/spot/XAU-USD-SPOTimport Decimal from "decimal.js";const API_BASE = "https://api.goldprice.dev";const API_KEY = process.env.GOLDPRICE_API_KEY;if (!API_KEY) {  throw new Error("GOLDPRICE_API_KEY not set");}const TTL_MS = 60_000;const cache = new Map();/** Fetch live spot price. Cached 60s per symbol, retries 3x on 429. */export async function spot(symbol = "XAU-USD-SPOT") {  const cached = cache.get(symbol);  if (cached && cached.expiresAt > Date.now()) {    return cached.data;  }  let lastErr;  for (let attempt = 0; attempt < 3; attempt++) {    const res = await fetch(`${API_BASE}/v1/spot/${symbol}`, {      headers: { "X-API-Key": API_KEY },      signal: AbortSignal.timeout(5000),    });    if (res.status === 429) {      lastErr = new Error("goldprice: 429 rate limited");      const backoffMs = 2 ** attempt * 1000; // 1s, 2s, 4s      await new Promise((resolve) => setTimeout(resolve, backoffMs));      continue;    }    if (!res.ok) {      throw new Error(`goldprice: unexpected status ${res.status}`);    }    const raw = await res.json();    const data = {      symbol: raw.symbol,      quoteCurrency: raw.quote_currency,      price: new Decimal(raw.price),      bid: raw.bid == null ? null : new Decimal(raw.bid),      ask: raw.ask == null ? null : new Decimal(raw.ask),      isStale: raw.is_stale,      computedAt: raw.computed_at,    };    cache.set(symbol, { data, expiresAt: Date.now() + TTL_MS });    return data;  }  throw lastErr;}

Run it

Import the module and call spot(). The first call hits the API; calls within 60 seconds return the cached Decimal without a network round-trip. Restarting the process clears the cache (in-process only), back it with Redis if you need cross-process sharing.

run.mjs
import { spot } from "./goldprice.mjs";const r = await spot("XAU-USD-SPOT");console.log(`${r.symbol}-${r.quoteCurrency}: ${r.price} (computed ${r.computedAt})`);// XAU-USD: 4012.75 (computed 2026-10-23T07:00:18.221118+00:00)

Switch currency or metal

Symbols are METAL-CURRENCY-SPOT. Pass any symbol from the 31 spot currencies to spot(). Each unique symbol caches independently in the Map, so a multi-currency dashboard polling 5 symbols at 60-second intervals fires 5 API calls/minute uncached and 0 cached.

goldprice.mjs · multi-currency
// USD spot, defaultawait spot("XAU-USD-SPOT");await spot("XAU-INR-SPOT");await spot("XAU-EUR-SPOT");// Silver in USDawait spot("XAG-USD-SPOT");

Expected output

JSON
{  "symbol": "XAU",  "quote_currency": "USD",  "unit": "troy_ounce",  "contract_type": "spot",  "price": "4012.75",  "is_stale": false,  "computed_at": "2026-10-23T07:00:18.221118+00:00"}

Stdout shows one line: symbol, quote currency, the price as a decimal.js Decimal, and the ISO 8601 computedAt timestamp. The plain object returned by spot() is what your downstream code consumes.

Common errors

CodeWhat you seeFix
401goldprice: unexpected status 401 on the first callAPI key missing or invalid. Confirm the variable is set: echo $GOLDPRICE_API_KEY. If empty, re-export from your dashboard. The module throws at import time when the env var is empty, so the failure surfaces immediately rather than mid-request.
429Three retries with backoff all return 429, then spot() rejectsYou hit the per-minute cap. The 60-second cache prevents this for steady polling; if a burst of distinct symbols arrives at once, stagger the calls. For sustained high-volume use, see /pricing for paid plans.
N/APrices look right but drift slightly after repeated arithmeticJavaScript Number is IEEE-754 float: 0.1 + 0.2 === 0.30000000000000004. Gold prices carry 2 decimal places, so summing thousands of values in Number introduces basis-point errors. Keep prices as decimal.js Decimal through arithmetic and only call .toString() or .toNumber() at the boundary where you display or serialize.

Going further

  • Persist the cache across processes, replace the Map with a Redis-backed cache so multiple workers share one warm price
  • Add a bars() wrapper for /v1/bars?symbol=XAU-USD-SPOT&interval=1d&from=...&to=... and feed the series into a backtest
  • Wire the client into an Express or Fastify route and serve internally for non-Node services
  • Collapse duplicate in-flight requests for the same cold symbol so a burst of callers triggers one fetch instead of many
  • Expose Prometheus metrics for cache hit rate, p50/p95 latency, and 429-retry counts

Questions

How often does the price update?

The spot endpoint refreshes every 60 seconds (live spot data; Free/keyless delayed 15 minutes, paid live). The 60-second TTL above matches that cadence, repeated spot() calls within the window return the cached Decimal without a network round-trip.

Will this fit the free tier with auto-refresh?

It depends on your call site. A service polling once per minute = 1,440 calls/day = ~43,000/month, well over the 5,000/month free tier. Cache aggressively and call only on demand. Polling once per hour = ~720/month, inside the free tier. For continuous high-volume use, see /pricing for paid plans.

Can I use this commercially?

Commercial use is allowed on every plan. Paid plans need no credit link; Free requires a visible link to goldprice.dev near the prices.

Why decimal.js instead of Number?

JavaScript's only numeric type is a 64-bit float, so arithmetic drifts on summation: 0.1 + 0.2 is 0.30000000000000004. Gold prices carry 2 decimal places; summing thousands of values in Number introduces basis-point errors over time. decimal.js keeps exact arithmetic, and the API returns prices as strings precisely so clients can construct a Decimal without loss.

Do I need TypeScript or a build step?

No. The sample above is plain ES modules (.mjs), which Node 18+ runs natively with no transpiler. If your project uses TypeScript, the same code works unchanged inside a .ts file, fetch, AbortSignal.timeout, and decimal.js all ship their own types.

What metals are supported?

Gold (XAU), silver (XAG), copper (HG), platinum and palladium are not offered on any tier. Substitute the metal code in the symbol, e.g. spot("XAG-USD-SPOT").

Is the free tier really free?

Yes, 5,000 calls/month, no credit card, no expiration. Get the key at /onboarding.

Can I have Claude write this for me?

Yes. Open Claude Desktop with the goldprice.dev MCP server installed and ask: Build a Node.js client for the goldprice.dev /v1/spot endpoint. Use native fetch, decimal.js, a 60-second Map-based cache, and retry-on-429 with exponential backoff. Read the API key from GOLDPRICE_API_KEY. The MCP server gives Claude the live schema, so generated code uses correct field names on first try.

Keep reading

Start with a free API key

5,000 requests a month on the free plan. No credit card.

Get a free key