To show the gold price in React, fetch /api/gold-price from a function component. Your Express server calls goldprice.dev at /v1/spot/XAU-USD-SPOT and keeps the API key in GOLDPRICE_API_KEY. Keep the returned price as a decimal string. Show its calculation time and stale flag, then refresh every sixty seconds. Free prices are delayed by fifteen minutes. The browser receives price data without the key.
Get your API key
Get a free key at goldprice.dev/onboarding. No credit card is required. Replace the placeholder below with your key, then run it in your terminal:
export GOLDPRICE_API_KEY=ga_live_replace_with_your_keyKeep this terminal open for the remaining steps. Never put the key in React code or a browser environment variable. Anyone who loads the page can inspect its JavaScript and network requests.
Create the React project
Use Node eighteen or newer with npm. Run these commands in Bash or zsh. They install React eighteen, Express and esbuild, then create the HTML page and React entry point.
The project uses ES modules. Save the next files in the gold-price-react folder created here.
mkdir gold-price-reactcd gold-price-reactnpm init -ynpm pkg set type=modulenpm install react@18 react-dom@18 express@5npm install --save-dev esbuild@0.25mkdir publiccat > public/index.html <<'HTML'<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gold price in React</title> </head> <body> <div id="root"></div> <script src="/app.js" defer></script> </body></html>HTMLcat > main.jsx <<'JSX'import { createRoot } from "react-dom/client";import GoldPrice from "./GoldPrice.jsx";createRoot(document.getElementById("root")).render(<GoldPrice />);JSXAdd the server route
Save this as server.js. The server reads GOLDPRICE_API_KEY, fetches the gold spot price and returns only price, computed_at and is_stale. The price stays a decimal string.
Express also serves the browser files, so /api/gold-price works without a separate proxy or CORS setup. Rate limit responses pass along Retry-After. Failed requests return an error message without exposing the key.
import express from "express";import { fileURLToPath } from "node:url";const key = process.env.GOLDPRICE_API_KEY;if (!key) throw new Error("Set GOLDPRICE_API_KEY before starting the server");const app = express();app.get("/api/gold-price", async (req, res) => { res.set("Cache-Control", "no-store"); try { const response = await fetch( "https://api.goldprice.dev/v1/spot/XAU-USD-SPOT", { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(10_000), } ); if (response.status === 429) { res.set("Retry-After", response.headers.get("Retry-After") || "60"); return res.status(429).json({ error: "Too many requests. Please wait." }); } if (response.status === 401) { return res.status(401).json({ error: "Check GOLDPRICE_API_KEY on the server." }); } if (!response.ok) { return res.status(502).json({ error: "The gold price could not be loaded." }); } const data = await response.json(); if ( typeof data.price !== "string" || !/^\d+(\.\d+)?$/.test(data.price) || typeof data.computed_at !== "string" || !Number.isFinite(Date.parse(data.computed_at)) || typeof data.is_stale !== "boolean" ) { throw new Error("Invalid price response"); } res.json({ price: data.price, computed_at: data.computed_at, is_stale: data.is_stale, }); } catch { res.status(502).json({ error: "The gold price is unavailable. Try again later." }); }});app.use(express.static(fileURLToPath(new URL("./public/", import.meta.url))));app.listen(3000, "127.0.0.1", () => { console.log("Open http://localhost:3000");});Add the gold price component
Save this as GoldPrice.jsx. The effect fetches immediately and refreshes every sixty seconds. It shows loading and error messages, the price in US dollars per troy ounce, and the computed_at timestamp.
Cleanup clears the interval and cancels any pending request. A failed refresh keeps the previous price visible with an error. A stale response shows a warning. After a rate limit response, the component reads Retry-After and waits before requesting again.
The visible goldprice.dev link near the price meets the Free plan attribution requirement.
import { useEffect, useState } from "react";export default function GoldPrice() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); useEffect(() => { let stopped = false; let pending = false; let controller; let retryAt = 0; async function refresh() { if (pending || Date.now() < retryAt) return; pending = true; setLoading(true); controller = new AbortController(); const request = controller; const timeout = setTimeout(() => request.abort(), 15_000); try { const response = await fetch("/api/gold-price", { signal: request.signal, cache: "no-store", }); if (response.status === 429) { const header = response.headers.get("Retry-After"); const seconds = header === null ? NaN : Number(header); const deadline = Number.isFinite(seconds) ? Date.now() + Math.max(0, seconds) * 1000 : Date.parse(header || ""); retryAt = Math.max( Date.now() + 60_000, Number.isFinite(deadline) ? deadline : 0 ); } if (!response.ok) { const problem = await response.json(); throw new Error(problem.error || "Cannot load the gold price."); } const next = await response.json(); if (!stopped) { setData(next); setError(""); } } catch (err) { if (!stopped) { setError(err.name === "AbortError" ? "The request timed out." : err.message); } } finally { clearTimeout(timeout); pending = false; if (!stopped) setLoading(false); } } refresh(); const interval = setInterval(refresh, 60_000); return () => { stopped = true; clearInterval(interval); controller?.abort(); }; }, []); return ( <section aria-label="Gold price"> <h2>Gold price</h2> {loading && <p role="status">Loading gold price...</p>} {error && <p role="alert">{error}</p>} {data && ( <> <p>USD {data.price} per troy ounce</p> <p>Price computed: <time dateTime={data.computed_at}>{data.computed_at}</time></p> {data.is_stale && <p role="status">This price is marked stale. Check the update time.</p>} </> )} <p>Free plan prices are delayed by fifteen minutes.</p> <p>Price data: <a href="https://goldprice.dev/docs/api-reference">goldprice.dev</a></p> </section> );}Build and open the page
In the same terminal, from gold-price-react, run the commands below. Open http://localhost:3000 in your browser. Express serves the built React app and its API route from the same origin.
Rebuild after changing browser code. Restart the server after changing its code or API key. The server listens locally for this tutorial.
npx esbuild main.jsx --bundle --jsx=automatic --minify --outfile=public/app.jsnode server.jsExpected output
{ "symbol": "XAU", "quote_currency": "USD", "unit": "troy_ounce", "contract_type": "spot", "price": "4023.54", "is_stale": false, "computed_at": "2026-10-23T10:51:32.965761+00:00"}This is an example response from the goldprice.dev spot endpoint. Your server returns only price, computed_at and is_stale. React displays the price and calculation time, with a warning when is_stale is true. Actual values change.
Common errors
| Code | What you see | Fix |
|---|---|---|
| 401 | The page says to check GOLDPRICE_API_KEY on the server | Set GOLDPRICE_API_KEY in the terminal that starts Express, using your actual key. Restart node server.js after changing it. Keep the key out of browser files. |
| 429 | The page says there are too many requests | The request reached a rate or quota limit. The component reads Retry-After and skips refreshes until that wait has passed. Reduce requests across tabs and visitors, or review plan limits. Do not retry in a tight loop. |
| 502 | The page says the gold price is unavailable | The server could not fetch or validate a price response. Check its network access and try again later. The component keeps any previous price visible and shows an error so an unsuccessful refresh is clear. |
| N/A | The page is blank or the API route cannot be found | Run the build command before starting Express, then open the Express address shown in the terminal. Do not open the HTML file directly or use a separate frontend server without configuring its API proxy. |
Going further
- Add a shared server cache and combine simultaneous requests before opening the page to more visitors
- Pause polling while the browser tab is hidden to save calls
- Add a daily chart with
/v1/barsusing the API reference - Use
/v1/convertfor prices per gram or kilogram - Compare the server setup with the Node tutorial