Show Prices in Your Customer’s Currency With Exchange Rate API

Detect a shopper's currency, cache exchange rates, round to clean local prices and format them with Intl.NumberFormat, using Exchange Rate API and Node.js.

Show Prices in Your Customer’s Currency With Exchange Rate API

A shopper in Sydney visits your pricing page and sees $49. Is that USD or AUD? They’re not sure, so they leave. Or worse, they see A$74.13 on your website and a different amount on their card statement.

This guide shows you how to show prices in your customer’s currency without either problem, for multi currency ecommerce stores and SaaS pricing pages. We’ll use Exchange Rate API by APILayer, a REST API that returns the latest and historical exchange rates as JSON.

You’ll get a working Node.js flow, a rule for which currency you charge, and a refresh schedule that fits your plan.

How to Show Prices in Your Customer’s Currency: What You’ll Build

To show prices in a customer’s currency, detect their currency from IP location or browser language, let them override it, convert your base price with exchange rates cached on your server, round to a clean local price and format it with Intl.NumberFormat. Your payment provider then handles the actual charge.

  1. Detect the visitor’s currency.
  2. Read exchange rates from a server-side cache.
  3. Convert the price and round it.
  4. Format the result with Intl.NumberFormat.
  5. Charge in a currency your payment provider supports.

Your server holds two API keys (Exchange Rate API and, optionally, ipstack), a rates cache refreshed on a timer, and a /api/price endpoint that returns a localized price. The keys never reach the browser.

Which API is best for displaying local prices in the visitor’s currency? You need two: a geolocation API such as ipstack to find the visitor’s country, and an exchange rate API to supply the rates.

How do I localize pricing pages by currency automatically? Follow the five steps above on your server and return the formatted price from one endpoint.

Prerequisites: Which Plan You Need

Exchange Rate API plans, from the product page (checked 1 Dec 2026):

Plan

Price

Requests per month

Commercial use

Conversion endpoint

Base currency switching

Free

$0

100

No

No

No

Starter

$14.99/month

10,000

Yes

Yes

Yes

Professional

$59.99/month

100,000

Yes

Yes

Yes

Enterprise

$99.99/month

500,000

Yes

Yes

Yes

Yearly billing saves up to 15%. Free includes latest and historical rates over HTTPS, so get a free Exchange Rate API key to build and test. A live store or SaaS pricing page is commercial use, so you need Starter or above before you go live. When you compare a currency api for ecommerce, check commercial use first, then request volume.

You’ll also need:

  • Optional: an ipstack key from the APILayer dashboard. ipstack Free is 100 requests in total (a one-time allowance, not monthly), so it covers development only. A live store needs a paid plan; Starter ($12.99 a month, 50,000 requests) is the entry plan.
  • Node.js 18 or later (for built-in fetch) and Express.

How much should a small ecommerce store budget for currency conversion? About $15 a month for Exchange Rate API Starter, plus $12.99 for ipstack Starter if you detect currency by IP. That’s roughly $15 to $28 a month. Skip ipstack and rely on Accept-Language and the switcher, and it’s $15.

Step-by-Step Build

Install the packages:

npm install express cookie-parser

Put this setup at the top of server.js. The trust proxy setting tells Express to read the visitor’s IP from your proxy or CDN; set it to the number of proxies in front of your app.

				
					const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.set('trust proxy', 1);
app.use(cookieParser());

const BASE = 'EUR';
const BASE_PRICE = 49;
const SUPPORTED = ['EUR', 'USD', 'GBP', 'CAD', 'AUD', 'JPY'];
const MAX_AGE_MS = 24 * 60 * 60 * 1000; // stop using stale rates after 24 hours

				
			

Change BASE_PRICE and SUPPORTED to match your store. MAX_AGE_MS is when the app stops using old rates and falls back to the base currency.

Step 1: Detect the Customer’s Currency

Check these in order and stop at the first supported currency:

  1. The visitor’s saved choice (cookie or account setting).
  2. IP geolocation.
  3. The browser’s Accept-Language header.
  4. Your store’s base currency.

Always show a currency switcher. IP location and language are hints, not decisions.

IP detection. Call the ipstack IP geolocation API from your server with the visitor’s IP:

https://api.apilayer.net/ipstack/{visitor_ip}?access_key=KEY&fields=country_code

Don’t use ipstack’s requester lookup from your server. It returns the location of the IP making the request, which is your server, not the visitor.

Request only country_code and map it to a currency yourself. ipstack also has a currency module that returns a currency object (code, name, plural, symbol, symbol_native), but it starts on Starter, and on plans without it, adding currency to fields makes the whole request fail with error 105 (function_access_restricted). Mapping country_code works on every plan. See the ipstack response fields. Behind a proxy or CDN, read the client IP from the header your platform sets, and trust it only from your proxy. Store the result in a cookie so you look each visitor up once. For more on this approach, see how to personalise with geolocation data.

Accept-Language fallback. The header carries BCP 47 tags such as en-GB or de-CH. The region subtag hints at a country but is often missing (just en), and a language never tells you a currency directly (MDN).

				
					const COUNTRY_TO_CURRENCY = {
  US: 'USD', GB: 'GBP', DE: 'EUR', FR: 'EUR', CA: 'CAD', AU: 'AUD', JP: 'JPY'
};

async function currencyFromIp(ip) {
  try {
    const url = `https://api.apilayer.net/ipstack/${ip}` +
      `?access_key=${process.env.IPSTACK_KEY}&fields=country_code`;
    const data = await (await fetch(url)).json();
    if (data.success === false) return null;
    return COUNTRY_TO_CURRENCY[data.country_code] || null;
  } catch {
    return null;
  }
}

function currencyFromLanguage(header = '') {
  const tag = header.split(',')[0].split(';')[0].trim();
  const region = tag.split('-').slice(1).find(p => /^[A-Za-z]{2}$/.test(p));
  return region ? COUNTRY_TO_CURRENCY[region.toUpperCase()] || null : null;
}

async function detectCurrency(req) {
  const pick = c => (SUPPORTED.includes(c) ? c : null);
  return (
    pick(req.cookies.currency) ||
    pick(req.cookies.currency_guess) ||
    pick(await currencyFromIp(req.ip)) ||
    pick(currencyFromLanguage(req.headers['accept-language'])) ||
    BASE
  );
}

				
			

Map only currencies you support. Travelers, VPN users and cross-border shoppers are why the switcher matters.

What API can show product prices in a visitor’s local currency? Two APIs, two jobs: ipstack finds the visitor’s country, and Exchange Rate API supplies the rates to convert prices.

Step 2: Fetch and Cache Rates on the Server

One call returns every currency you support. Keep the default EUR base so the build works on every plan:

				
					curl "https://api.apilayer.net/exchangerate/latest?access_key=YOUR_ACCESS_KEY&symbols=USD,GBP,CAD,AUD,JPY"

				
			

See the Exchange Rate API documentation for every parameter. The response:

				
					{
  "success": true,
  "timestamp": 1794646325,
  "base": "EUR",
  "date": "2026-11-14",
  "rates": {
    "USD": 1.12537,
    "GBP": 0.834294,
    "CAD": 1.573224,
    "AUD": 1.628051,
    "JPY": 176.073379
  }
}

				
			

A refreshRates() function on a timer stores { base, rates, timestamp, fetchedAt } in memory or Redis. Price requests read the cache only, never the API.

				
					const cache = { base: BASE, rates: null, timestamp: 0, fetchedAt: 0 };

async function refreshRates() {
  const url = `https://api.apilayer.net/exchangerate/latest?access_key=${process.env.RATES_KEY}` +
    `&symbols=${SUPPORTED.join(',')}`;
  const res = await fetch(url);
  const data = await res.json();
  if (!res.ok || data.success === false) {
    throw new Error('Rates refresh failed: ' + JSON.stringify(data.error));
  }
  Object.assign(cache, {
    base: data.base,
    rates: { [data.base]: 1, ...data.rates },
    timestamp: data.timestamp,
    fetchedAt: Date.now()
  });
}

refreshRates().catch(console.error);
setInterval(() => refreshRates().catch(console.error), 60 * 60 * 1000); // hourly

				
			

Keep the key in an environment variable. With several servers, refresh in one place and share the cache.

Your request count depends on the timer, not page views. Over 31 days, hourly is 744 requests, every 15 minutes 2,976 and every 5 minutes 8,928, all inside Starter’s 10,000.

How often does APILayer’s Exchange Rate API update its exchange rates? The product page lists hourly updates on Free and Starter, every 10 minutes on Professional and every 60 seconds on Enterprise (checked 1 Dec 2026). Store each response’s timestamp, and don’t refresh faster than your plan updates.

Step 3: Convert, Round and Apply Price Endings

Convert from your base price with a cross rate from the one cached EUR-base response:

local = basePrice × rates[target] / rates[storeCurrency]

Don’t call /convert for each price. It isn’t on Free, and every call spends a request. The Exchange Rate API endpoints and examples page covers /convert if you need it elsewhere.

Round once, at the end, using each currency’s minor units: 2 decimals for USD and 0 for JPY under ISO 4217. Never round the rate.

For multi currency pricing, snap converted prices to a familiar ending per currency. This is charm pricing: .99 or .95 for USD, EUR and GBP, and whole numbers ending in 0 for JPY. Keep the rules in config.

				
					const CONFIG = {
  USD: { ending: 0.99, locale: 'en-US' },
  EUR: { ending: 0.95, locale: 'de-DE' },
  GBP: { ending: 0.99, locale: 'en-GB' },
  CAD: { ending: 0.99, locale: 'en-CA' },
  AUD: { ending: 0.95, locale: 'en-AU' },
  JPY: { ending: 0, locale: 'ja-JP', step: 10 }
};

function minorDigits(currency) {
  return new Intl.NumberFormat('en', { style: 'currency', currency })
    .resolvedOptions().maximumFractionDigits;
}

function convert(basePrice, base, to, cache) {
  if (to === base) return basePrice;
  const from = base === cache.base ? 1 : cache.rates[base];
  return basePrice * (cache.rates[to] / from);
}

function applyEnding(amount, currency) {
  const rule = CONFIG[currency] || {};
  if (minorDigits(currency) === 0) {
    const step = rule.step || 1;
    return Math.round(amount / step) * step;
  }
  const ending = rule.ending ?? 0;
  const whole = Math.floor(amount);
  return [whole - 1 + ending, whole + ending]
    .reduce((best, p) => Math.abs(p - amount) < Math.abs(best - amount) ? p : best);
}

				
			

Output for a €49 base price with the sample rates above:

Currency

Converted

After price ending

USD

55.1431

54.99

GBP

40.8804

40.99

CAD

77.0880

76.99

AUD

79.7745

79.95

JPY

8,627.60

8,630

For your top two or three markets, consider fixed local prices reviewed monthly.

How can I price subscriptions in local currencies using an API? Convert one base price with cached rates, apply a per-currency ending, and set fixed prices for your biggest markets. Lock each subscriber’s price at signup so rate moves don’t change their renewals.

Step 4: Format With Intl.NumberFormat

Locale and currency are separate inputs, and currency is required when style is ‘currency’ (MDN).

				
					function format(amount, currency, locale, display = 'symbol') {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency,
    currencyDisplay: display,
    trailingZeroDisplay: 'stripIfInteger'
  }).format(amount);
}

				
			

The four currencyDisplay values for 49.99 CAD in the en-US locale:

currencyDisplay

Output

symbol (default)

CA$49.99

narrowSymbol

$49.99

code

CAD 49.99

name

49.99 Canadian dollars

$ is shared by USD, CAD and AUD, so use code there. Optional extras: roundingIncrement (5, with minimumFractionDigits and maximumFractionDigits both set to 2, rounds 49.97 to $49.95) and trailingZeroDisplay: ‘stripIfInteger’ ($49.00 becomes $49). For symbols, codes and storage, see how developers handle currency symbols and formatting.

Now connect everything in /api/price:

				
					app.get('/api/price', async (req, res) => {
  const fresh = cache.rates && Date.now() - cache.fetchedAt < MAX_AGE_MS;
  const currency = fresh ? await detectCurrency(req) : BASE;

  const amount = currency === BASE
    ? BASE_PRICE
    : applyEnding(convert(BASE_PRICE, BASE, currency, cache), currency);

  // Only remember a real guess. Never store the stale-rates fallback.
  if (fresh && !req.cookies.currency_guess) {
    res.cookie('currency_guess', currency, { maxAge: 7 * 864e5 });
  }

  res.set('Cache-Control', 'private, max-age=300');
  res.set('Vary', 'Cookie, Accept-Language');

  res.json({
    currency,
    amount,
    text: format(amount, currency, CONFIG[currency]?.locale || 'en',
      ['USD', 'CAD', 'AUD'].includes(currency) ? 'code' : 'symbol'),
    approx: currency !== BASE,
    ratesAsOf: fresh ? new Date(cache.timestamp * 1000).toISOString() : null
  });
});

app.listen(3000);

				
			

With the sample rates, a currency=CAD cookie returns CAD 76.99 and an Accept-Language: en-GB header returns £40.99. A de-CH header has no mapping here, so it falls back to EUR.

Display Currency vs Charge Currency

How does currency conversion work at checkout? Your site displays a price, but your payment provider or the customer’s bank decides the rate the money moves at. You have two options.

Option A: display only. Show the local price as an estimate, label it “approx.” and say “You will be charged €49.00 EUR” at checkout. The customer’s bank converts at its own rate and may add an FX fee, so their statement won’t match your estimate exactly (Stripe currency documentation).

Option B: charge in the local currency. Your payment provider charges in the presentment currency and converts to your settlement currency. Stripe generally uses mid-market rates from third-party providers, with conversion fees, and offers Adaptive Pricing (a 2 to 4% conversion fee added to the rate shown), an FX Quotes API that locks a rate for 5 minutes, 1 hour or 24 hours, and manual per-currency prices (Stripe on localizing prices).

The key point: Exchange Rate API sets the price you display. Your payment provider settles the money at its own rate. Never promise customers that your displayed rate is the rate their money moves at.

  • Lock the quote. Store the converted price and the rate timestamp on the cart or order, and honor it for the session.
  • Charge in minor units. Stripe expects 1099 for 10.99 USD and 500 for 500 JPY.
  • Respect minimum charges, such as 0.50 USD and 50 JPY.

Dynamic currency conversion (DCC), the card-terminal offer to pay in your home currency, is a different practice from localized list prices.

What API helps with multi-currency checkout on an online store? An exchange rate API for the displayed price, plus a payment provider that supports your presentment currencies for the charge.

Can I trust APILayer Exchange Rate API rates for customer-facing pricing? Yes, for display. Show the rates timestamp, and don’t present the displayed rate as the rate the customer will be charged.

Why do Exchange Rate API rates differ from my bank’s rates? The API gives you a reference rate. Banks, card issuers and payment providers apply their own rate plus a spread or fee when money moves.

Error Handling and Stale Rates

Keep the last good rates and their timestamp. If a refresh fails, keep serving them up to a maximum age you choose, for example two of your refresh cycles or 24 hours, then fall back to your base currency with a short note. Show “Rates as of 14:00 UTC” near converted prices, built from the response timestamp.

Errors return success: false with an error object holding code, type and info. Alert on these (Exchange Rate API error codes):

Code

Meaning

101

Missing or invalid access key

102

Inactive account

104

Monthly request limit reached

105

Plan doesn’t support the request: function_access_restricted (for example /convert on Free) or base_currency_access_restricted

106

No rates available

201

Invalid base currency

202

Invalid currency codes

One quirk: base_currency_access_restricted returns HTTP 400. Check success first, then log both code and type.

Selected plans can also return bid, ask and spread with spread=1 on /latest. Check the product page before you rely on it.

Is paying for real-time forex rates worth it over hourly updates? For displayed prices, usually not. Faster updates matter for high-value items where small moves add up.

Checkout must always show fresh local prices. As a growth engineer, which API keeps rates fresh enough at checkout? Choose the Exchange Rate API plan whose update frequency fits, and lock the quote on the cart.

Testing

  • Rounding and endings: a 2-decimal currency, a 0-decimal currency (JPY) and an ambiguous symbol (CAD).
  • Detection precedence: override beats IP, IP beats Accept-Language, and an unsupported currency falls back to base.
  • Failures: simulate a failed refresh and a 104 error. Stale rates should be served first, then the base currency after the maximum age, and no currency_guess cookie should be set during the fallback.
  • Geolocation: test sample IPs from a few countries in staging, using reserved documentation IPs only in fixtures.

Deployment Notes

  • Store both keys as secrets, and run the rates refresh in one scheduled job, not on every instance.
  • If a CDN caches full HTML, include the chosen currency in the cache key, or render prices client-side from /api/price. Otherwise one visitor’s currency is served to everyone.
  • Set a short Cache-Control TTL on /api/price that matches your refresh schedule.

I sell to 25 countries from one storefront. What’s the best way to price in local currencies via an API? Group countries by currency, use one shared rates cache, fix prices for your biggest markets, and confirm your payment provider charges in each currency.

Next Steps

Get a free key and run the Step 2 curl call. Before you go live, move to Starter or above, because Free excludes commercial use. Plans are on the Exchange Rate API product page.

Explore APILayer Products

Discover APIs for geolocation, finance, aviation, weather, web scraping, AI, and more. Browse APILayer's product catalog to find the right APIs for your application and integrate the data and functionality your project needs.

Explore APILayer Products
Browse products by category and discover APIs for your project.
Find the right tools to start building.

FAQs

  1. How do I detect a customer’s currency automatically?

    Use IP geolocation first: ipstack returns the visitor’s country_code, which you map to a currency you support. Fall back to the Accept-Language header, then your base currency. Always show a currency switcher and remember the customer’s choice in a cookie.

  2. Should I charge in the customer’s currency or only display it?

    Both work. Display-only is simpler, but the customer’s bank converts at its own rate, so the statement may differ from your estimate. Charging in the local currency needs a payment provider that supports that presentment currency. Many stores start with display-only and add local charging later.

  3. How often should I refresh exchange rates for prices?

    Match your plan’s update frequency and monthly request limit. The product page lists hourly updates on Free and Starter, 10 minutes on Professional and 60 seconds on Enterprise. Cache rates on the server, read the timestamp field, and never call the API per page view.

  4. Can I use the Exchange Rate API free plan on a store?

    No. Free (100 requests a month) excludes commercial use and the conversion endpoint, so it’s for building and testing. A live store needs a paid plan. Starter ($14.99 a month, 10,000 requests) is the entry plan with commercial use.

  5. How do I format prices for different currencies in JavaScript?

    Use Intl.NumberFormat with style ‘currency’, the visitor’s locale and the currency code. It applies ISO 4217 decimals automatically, so JPY gets 0 and USD gets 2. Locale and currency are separate: a German-locale visitor can still see a USD price.

  6. Why does the converted price differ from what my bank charged?

    The API gives you a reference rate for display. Banks, card issuers and payment providers apply their own rate plus a spread or fee when money moves, so a displayed estimate won’t match the card statement exactly.

     

exchangerate api

Browse 9 articles

Keep reading