If you convert prices in a React component with useEffect, users see USD flash to EUR, crawlers see USD, and your API key ends up near the browser. React Router v7 (the successor to Remix) gives you a better place: the loader. It runs on the server, so the HTML arrives with the right price already in it.

This post covers a server-only rate module, a cookie for the visitor's currency, an action to change it, formatting that does not cause hydration mismatches, and cache headers that do not leak one visitor's currency to another.

Project setup

Any React Router v7 app in framework mode works:

npx create-react-router@latest shop cd shop 

Add your key to .env. We use AllRatesToday for live mid-market rates; a free API key is enough to follow along.

ALLRATES_API_KEY=art_live_xxxxxxxx 

A server-only rate module

The .server.ts suffix tells React Router to keep this file out of the client bundle. If you import it from client code by mistake, the build fails instead of shipping your key.

// app/lib/rates.server.ts const API_URL = "https://allratestoday.com/api/v1/rates"; const TTL_MS = 10 * 60 * 1000; export const SUPPORTED = ["USD", "EUR", "GBP", "JPY", "CAD", "AUD"] as const; export type Currency = (typeof SUPPORTED)[number]; type RateTable = { rates: Record<string, number>; time: string }; type Entry = { table: RateTable; fetchedAt: number }; const cache = new Map<string, Entry>(); const inflight = new Map<string, Promise<RateTable>>(); async function fetchTable(base: Currency): Promise<RateTable> { const url = new URL(API_URL); url.searchParams.set("source", base); url.searchParams.set("target", SUPPORTED.filter((c) => c !== base).join(",")); const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.ALLRATES_API_KEY}` }, signal: AbortSignal.timeout(5000), }); if (res.status === 401) throw new Error("Rates API: bad or missing key"); if (res.status === 429) throw new Error("Rates API: rate limited"); if (!res.ok) throw new Error(`Rates API: HTTP ${res.status}`); const rows: { rate: number; target: string; time: string }[] = await res.json(); return { rates: Object.fromEntries([[base, 1], ...rows.map((r) => [r.target, r.rate])]), time: rows[0]?.time ?? new Date().toISOString(), }; } export async function getRateTable(base: Currency = "USD"): Promise<RateTable | null> { const hit = cache.get(base); if (hit && Date.now() - hit.fetchedAt < TTL_MS) return hit.table; let pending = inflight.get(base); if (!pending) { pending = fetchTable(base).finally(() => inflight.delete(base)); inflight.set(base, pending); } try { const table = await pending; cache.set(base, { table, fetchedAt: Date.now() }); return table; } catch (err) { console.error(err); return hit?.table ?? null; // stale beats broken } } 

The upstream response is a JSON array, one row per target. All targets in one call count as one request, so we fetch every supported currency together and cache the table for 10 minutes. Rates refresh upstream about every 60 seconds, which is far more often than a product page needs.

A cookie for the chosen currency

// app/lib/currency-cookie.server.ts import { createCookie } from "react-router"; import { SUPPORTED, type Currency } from "./rates.server"; export const currencyCookie = createCookie("currency", { path: "/", sameSite: "lax", maxAge: 60 * 60 * 24 * 365, }); export async function readCurrency(request: Request): Promise<Currency> { const value = await currencyCookie.parse(request.headers.get("Cookie")); return SUPPORTED.includes(value) ? value : "USD"; } 

The loader: convert on the server

// app/routes/pricing.tsx import { data, Form, redirect } from "react-router"; import type { Route } from "./+types/pricing"; import { getRateTable, SUPPORTED } from "~/lib/rates.server"; import { currencyCookie, readCurrency } from "~/lib/currency-cookie.server"; const PLANS = [ { id: "starter", name: "Starter", usd: 19 }, { id: "team", name: "Team", usd: 49 }, { id: "business", name: "Business", usd: 149 }, ]; const LOCALE: Record<string, string> = { USD: "en-US", EUR: "de-DE", GBP: "en-GB", JPY: "ja-JP", CAD: "en-CA", AUD: "en-AU", }; export async function loader({ request }: Route.LoaderArgs) { const wanted = await readCurrency(request); const table = await getRateTable("USD"); // No rates at all? Show USD rather than failing the page. const currency = table?.rates[wanted] ? wanted : "USD"; const rate = table?.rates[currency] ?? 1; const fractionDigits = new Intl.NumberFormat("en", { style: "currency", currency }) .resolvedOptions().maximumFractionDigits ?? 2; const factor = 10 ** fractionDigits; return data( { currency, locale: LOCALE[currency], rateTime: table?.time ?? null, plans: PLANS.map((p) => ({ ...p, amount: Math.round(p.usd * rate * factor) / factor, })), }, { headers: { // Response depends on a cookie: never let a shared cache store it. "Cache-Control": "private, max-age=60", Vary: "Cookie", }, }, ); } export function headers({ loaderHeaders }: Route.HeadersArgs) { return loaderHeaders; } 

Three decisions worth calling out:

  1. The loader returns numbers, rounded to the currency's minor unit. resolvedOptions().maximumFractionDigits is 0 for JPY and 2 for EUR, so there is no hardcoded list.
  2. The locale comes from the server. If the component used navigator.language, the server would render €45.08 and the browser would hydrate 45,08 €, and React would log a hydration mismatch. Passing the locale down keeps both renders identical.
  3. private in Cache-Control. The same URL returns different HTML per cookie. A CDN that caches it publicly would show one visitor's EUR prices to the next visitor. private keeps it in the browser cache only.

The headers export is required. Loader headers apply to data requests, but the document response only gets the headers you return from headers.

The action: switch currency

// app/routes/pricing.tsx (continued) export async function action({ request }: Route.ActionArgs) { const form = await request.formData(); const value = String(form.get("currency")); const currency = (SUPPORTED as readonly string[]).includes(value) ? value : "USD"; return redirect("/pricing", { headers: { "Set-Cookie": await currencyCookie.serialize(currency) }, }); } 

After the action, React Router revalidates the loader, so the new prices appear without a full page reload. Without JavaScript, the same <Form> is a normal POST and still works.

The component: format only

// app/routes/pricing.tsx (continued) export default function Pricing({ loaderData }: Route.ComponentProps) { const { currency, locale, plans, rateTime } = loaderData; const fmt = new Intl.NumberFormat(locale, { style: "currency", currency }); return ( <main> <Form method="post"> <label> Currency{" "} <select name="currency" defaultValue={currency} onChange={(e) => e.currentTarget.form?.requestSubmit()} > {SUPPORTED_CLIENT.map((c) => ( <option key={c} value={c}>{c}</option> ))} </select> </label> <noscript><button type="submit">Update</button></noscript> </Form> {plans.map((plan) => ( <section key={plan.id}> <h2>{plan.name}</h2> <p>{fmt.format(plan.amount)} / month</p> </section> ))} {currency !== "USD" && rateTime && ( <small> Approximate, converted at live mid-market rates ({new Date(rateTime).toUTCString()}). Billed in USD. </small> )} </main> ); } const SUPPORTED_CLIENT = ["USD", "EUR", "GBP", "JPY", "CAD", "AUD"]; 

SUPPORTED_CLIENT is a separate constant because the component cannot import values from a .server.ts file. In a bigger app, move the list to a shared app/lib/currencies.ts with no secrets in it and import it from both sides.

Parent routes and caching

If the pricing route sits under a layout with its own loader, both loaders run in parallel on navigation. Keep the rate lookup in the route that needs it. A layout loader that fetches rates "just in case" adds latency to every page.

For CDN caching, there are two clean options:

  • Keep private as above. Simple and correct.
  • Put the currency in the URL (/pricing?currency=EUR or /eur/pricing). Then the response no longer depends on a cookie, and you can send public, s-maxage=600, stale-while-revalidate=60.

The second option is also better for SEO if you want localized prices indexed. The local-currency pricing docs show the same idea for Next.js.

Deploying to many regions

On serverless or edge runtimes, the module-level Map survives only while an instance is warm. That is fine at low traffic. At higher traffic, swap the Map for your platform's KV or Redis and keep the same getRateTable signature, so no route code changes.

FAQ

Can I use clientLoader instead?
Not for this. A clientLoader runs in the browser, and the keyed API sends no CORS headers. Your key must stay in server code.

Why round in the loader instead of the component?
So the number you show is the number you would charge. If you later send amount to checkout, it is already at the correct precision.

Does this work in Remix v2?
Mostly. Replace react-router imports with @remix-run/node, and use json() instead of data() and LoaderFunctionArgs instead of the generated Route types.

How do I test the loader?
Call it directly: await loader({ request: new Request("http://x/pricing", { headers: { Cookie: "..." } }), params: {}, context: {} }) with fetch mocked. No browser needed.