Show Prices in the Visitor’s Local Currency: Static Sites, React, Next.js, WordPress

Step by step: detect a visitor’s currency and show an estimated local price on any website. Code for a plain HTML site, React and Next.js, with links for WordPress, WooCommerce and Shopify.

By Madhushan, Founder & Lead Developer ·

A visitor from Germany looking at a $49 plan wants to know roughly what that is in euros. This guide shows how to detect the visitor's currency and show an estimated local price next to yours, on a plain HTML site, in React and in Next.js. For WordPress, WooCommerce and Shopify there are dedicated guides, linked below.

Before you start

Which option fits your site

Your siteSimplest optionSection
Any site, you only want a converter on the pageEmbed the widgetOption 1
Plain HTML, PHP templates, Astro, Hugo, JekyllA rate proxy and 20 lines of JavaScriptOption 2
React or Next.jsAn API route and a client componentOption 3
WordPress or WooCommerceThe plugin, or a server-side PHP filterWordPress guide
ShopifyA Custom Liquid block and a WorkerShopify guide

Option 1: Embed a converter

If a converter next to the price is enough, paste the widget where it should appear. It is pre-filled with your price and uses the European Central Bank's daily reference rates (30+ major currencies). Keep the credit link visible.

<div class="art-currency-widget" data-base="USD" data-target="EUR" data-amount="49"></div>
<a href="https://allratestoday.com">Exchange rates by AllRatesToday</a>
<script async src="https://allratestoday.com/widget.js"></script>

Don't add data-api-key on a public site: the key would be visible in your page source. All attributes are in the widget reference.

Option 2: Estimated local price on any site

  1. Test your key

    Run this once from a terminal, with your key in place of the example:

    curl -H "Authorization: Bearer art_live_your_key" \
      "https://allratestoday.com/api/v1/rates?source=USD&target=EUR"

    You should see: [{"rate":0.86…,"source":"USD","target":"EUR","time":"…"}].

  2. Deploy a rate proxy

    The proxy keeps your key private and caches each currency pair for 15 minutes, so a busy site still makes only a few thousand calls a month. A Cloudflare Worker on the free plan is enough. Add your key as the secret ALLRATES_KEY and your site's address as SITE_ORIGIN.

    // Cloudflare Worker: holds your key, caches each pair for 15 minutes.
    export default {
      async fetch(req, env, ctx) {
        const url = new URL(req.url);
        const from = (url.searchParams.get('from') || '').toUpperCase();
        const to = (url.searchParams.get('to') || '').toUpperCase();
        if (!/^[A-Z]{3}$/.test(from) || !/^[A-Z]{3}$/.test(to)) {
          return new Response('{"error":"from and to must be ISO 4217 codes"}', { status: 400 });
        }
    
        const cacheKey = new Request(`https://rates.internal/${from}-${to}`);
        let res = await caches.default.match(cacheKey);
        if (!res) {
          const r = await fetch(
            `https://allratestoday.com/api/v1/rates?source=${from}&target=${to}`,
            { headers: { Authorization: `Bearer ${env.ALLRATES_KEY}` } }
          );
          if (!r.ok) return new Response('{"error":"rate unavailable"}', { status: 502 });
          const [{ rate, time }] = await r.json();
          res = new Response(JSON.stringify({ from, to, rate, time }), {
            headers: { 'Content-Type': 'application/json', 'Cache-Control': 'max-age=900' },
          });
          ctx.waitUntil(caches.default.put(cacheKey, res.clone()));
        }
        const out = new Response(res.body, res);
        out.headers.set('Access-Control-Allow-Origin', env.SITE_ORIGIN); // e.g. https://example.com
        return out;
      },
    };

    Already have a Node server? The same route in Express:

    // Node + Express: the same proxy on your own server.
    import express from 'express';
    const app = express();
    const cache = new Map(); // "USD-EUR" -> { body, expires }
    
    app.get('/api/rate', async (req, res) => {
      const from = String(req.query.from || '').toUpperCase();
      const to = String(req.query.to || '').toUpperCase();
      if (!/^[A-Z]{3}$/.test(from) || !/^[A-Z]{3}$/.test(to)) {
        return res.status(400).json({ error: 'from and to must be ISO 4217 codes' });
      }
      const key = `${from}-${to}`;
      const hit = cache.get(key);
      if (hit && hit.expires > Date.now()) return res.json(hit.body);
    
      const r = await fetch(`https://allratestoday.com/api/v1/rates?source=${from}&target=${to}`, {
        headers: { Authorization: `Bearer ${process.env.ALLRATES_KEY}` },
      });
      if (!r.ok) return res.status(502).json({ error: 'rate unavailable' });
      const [{ rate, time }] = await r.json();
      const body = { from, to, rate, time };
      cache.set(key, { body, expires: Date.now() + 15 * 60 * 1000 });
      res.json(body);
    });
    
    app.listen(3000);

    You should see: opening /api/rate?from=USD&to=EUR on your proxy returns from, to, rate and time.

  3. Add the snippet to your page

    Put your price in data-amount and its currency in data-currency. If the proxy is on another domain (a Worker), use its full address instead of /api/rate.

    <p class="price" data-amount="49.00" data-currency="USD">$49.00</p>
    <p class="local-price" hidden></p>
    
    <script>
    (async () => {
      const price = document.querySelector('.price');
      const out = document.querySelector('.local-price');
      try {
        // 1. The visitor's currency, from their IP
        const { currency } = await fetch('https://allratestoday.com/api/open/geo').then(r => r.json());
        if (!currency || currency === price.dataset.currency) return;
    
        // 2. The rate, through your proxy (the key stays on the server)
        const { rate } = await fetch(
          '/api/rate?from=' + price.dataset.currency + '&to=' + currency
        ).then(r => r.json());
        if (!rate) return;
    
        // 3. Format it the way the visitor expects
        const local = new Intl.NumberFormat(navigator.language, { style: 'currency', currency })
          .format(price.dataset.amount * rate);
        out.textContent = 'About ' + local + ' (you pay in ' + price.dataset.currency + ')';
        out.hidden = false;
      } catch (e) { /* show the original price only */ }
    })();
    </script>

    The visitor's currency comes from /api/open/geo, which answers {"country":"DE","currency":"EUR"} and can be called from the browser. Visitors who already use your currency see nothing extra.

  4. Check it from another country

    Open the page through a VPN or ask a colleague abroad.

    You should see: "About 42,10 € (you pay in USD)" under the price, formatted for the visitor's language.

Option 3: React and Next.js

  1. Add a server route

    In Next.js, a route handler holds the key. Put ALLRATES_KEY in .env.local and in your host's environment variables. Never prefix it with NEXT_PUBLIC_, which would ship it to the browser.

    // app/api/rate/route.ts  (Next.js App Router)
    const cache = new Map<string, { body: object; expires: number }>();
    
    export async function GET(req: Request) {
      const { searchParams } = new URL(req.url);
      const from = (searchParams.get('from') ?? '').toUpperCase();
      const to = (searchParams.get('to') ?? '').toUpperCase();
      if (!/^[A-Z]{3}$/.test(from) || !/^[A-Z]{3}$/.test(to)) {
        return Response.json({ error: 'from and to must be ISO 4217 codes' }, { status: 400 });
      }
    
      const key = `${from}-${to}`;
      const hit = cache.get(key);
      if (hit && hit.expires > Date.now()) return Response.json(hit.body);
    
      const r = await fetch(
        `https://allratestoday.com/api/v1/rates?source=${from}&target=${to}`,
        { headers: { Authorization: `Bearer ${process.env.ALLRATES_KEY}` }, cache: 'no-store' }
      );
      if (!r.ok) return Response.json({ error: 'rate unavailable' }, { status: 502 });
      const [{ rate, time }] = await r.json();
      const body = { from, to, rate, time };
      cache.set(key, { body, expires: Date.now() + 15 * 60 * 1000 });
      return Response.json(body, { headers: { 'Cache-Control': 'public, s-maxage=900' } });
    }

    In a Vite or Create React App project, use the Worker or Express proxy from Option 2 instead.

  2. Add a client component

    // components/LocalPrice.tsx
    'use client';
    import { useEffect, useState } from 'react';
    
    export function LocalPrice({ amount, currency }: { amount: number; currency: string }) {
      const [local, setLocal] = useState<string | null>(null);
    
      useEffect(() => {
        let cancelled = false;
        (async () => {
          try {
            const geo = await fetch('https://allratestoday.com/api/open/geo').then(r => r.json());
            if (!geo.currency || geo.currency === currency) return;
            const { rate } = await fetch(`/api/rate?from=${currency}&to=${geo.currency}`).then(r => r.json());
            if (!cancelled && rate) {
              setLocal(new Intl.NumberFormat(navigator.language, { style: 'currency', currency: geo.currency })
                .format(amount * rate));
            }
          } catch { /* keep the original price only */ }
        })();
        return () => { cancelled = true; };
      }, [amount, currency]);
    
      return (
        <span>
          {new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount)}
          {local && <small> (about {local})</small>}
        </span>
      );
    }
    
    // Usage: <LocalPrice amount={49} currency="USD" />

    The original price renders on the server, so there is no layout shift for search engines or slow connections. The estimate appears once the two requests finish.

  3. Or use the ready-made component

    react-currency-localizer-realtime packages the same pattern as a component and hooks, with caching and fallbacks built in:

    import { LocalizedPrice } from 'react-currency-localizer-realtime';
    
    <LocalizedPrice basePrice={49} baseCurrency="USD" />

    Its apiKey prop runs in the browser, so on a public site leave it out or point the package at your own proxy. See its README for the options.

Rules that keep it correct

If something goes wrong

What you seeWhat to do
Browser console shows a CORS error on /api/v1/ratesThe page is calling the API directly. Call your proxy instead; the keyed endpoints are server-to-server.
CORS error on your WorkerSITE_ORIGIN must match your site's address exactly, for example https://example.com, with no trailing slash.
Converted price far too big or smallThe pair is the wrong way round. from is your price's currency, to the visitor's.
Proxy returns "rate unavailable"The proxy could not reach the API with its key. Check the ALLRATES_KEY secret, or look for a 401 or 429 in its logs.
No estimate appearsThe visitor already uses your currency, or a request failed. Check the browser's network tab.
Your key shows up in the page sourceIt was put in front-end code or a NEXT_PUBLIC_ variable. Move it to the server and rotate the key from your profile.

Which plan do I need?

OptionPlanTypical usage
Converter widgetNone (ECB rates, credit link)Unmetered
Estimated local price, personal or test siteFree keyA few calls a day while you build
Estimated local price on a commercial sitePaid plan, from €4.99/moUp to about 2,900 calls/mo per currency pair per cache location (15-minute cache)

Build and test on the free API key. Plans and limits are on the pricing page.

FAQ

Can I call the API straight from the browser?

Not the keyed endpoints. They send no CORS headers, and a key in front-end code can be copied by anyone. Use a server route, as in every example above.

How accurate is the visitor's currency?

It comes from the country of the visitor's IP address. VPNs and travellers will see the currency of the country they appear to be in, which is why the estimate sits next to your real price rather than replacing it.

How often should the rate refresh?

For a displayed estimate, every 15 minutes to an hour is plenty. Mid-market rates move by fractions of a percent in that time.

Does this work with static site generators?

Yes. The price is in your HTML at build time; the estimate is added in the browser, and the proxy runs separately (a Worker or any small server).

Show your prices in every currency

Free key in 30 seconds, no credit card.

Get free API key Read the docs

Related

More: widget reference · SDKs · developer hub · API documentation.