Exchange rates in Next.js and TypeScript
Fetch live exchange rates from a Next.js Server Component, keep the API key off the client, and cache the response without hiding when the underlying rate last changed.
Call exchangerate.dev from a Server Component or Route Handler, never from browser code that contains your key. Next.js can revalidate the upstream request every 60 seconds while the response fields source, market_session, and data_updated_at tell your UI what the cached rate actually represents.
EXCHANGERATE_API_KEY in a server-only environment variable. Never prefix it with NEXT_PUBLIC_.fetch with next: { revalidate: 60 } to avoid one upstream request per page view.data_updated_at rather than treating the response timestamp as proof that the market observation is fresh.Fetch from the server side
A Server Component runs outside the browser, so it can read a private environment variable. The example below requests only EUR and GBP against USD, checks the HTTP status, and returns typed JSON to the page.
Cache the request, preserve the observation time
next: { revalidate: 60 } gives the upstream request a cache lifetime of at most 60 seconds. That reduces duplicate calls across page views. It does not make a daily reference rate intraday-fresh, so keep source, market_session, and data_updated_at beside the value.
NEXT_PUBLIC_ can be included in browser bundles. Name this secret EXCHANGERATE_API_KEY and read it only from server code. Anonymous calls are fine for a quick test, but production code should use a key.Separate display currency from settlement currency
A storefront can use an indicative rate to show an approximate local price. The final charge must come from the payment provider or dealing venue because fees, spreads, rounding, and settlement timing can change the executable amount.
- Keep the API key on the server.
- Cache successful responses, not 401 or 429 errors.
- Show the rate source and observation time when freshness matters.
- Keep the original product price and currency as the settlement source of truth.