You have an Express app that stores prices in USD, and now some pages need to show EUR, GBP or JPY. Converting inside every route handler gets messy fast. A single middleware that puts a price() helper on res.locals keeps the conversion in one place.

This post builds that middleware for Express 5 on Node 22. It covers picking the visitor's currency, an in-memory cache that refreshes every 10 minutes, and what happens when the rate API is down.

What we are building

After the middleware runs, every template and route gets three things:

  • res.locals.currency: the currency for this request, like "EUR"
  • res.locals.convert(amountUsd): a number in the target currency
  • res.locals.price(amountUsd): a formatted string, like "€45.99"

In a template that reads like this:

<p class="price"><%= price(product.priceUsd) %></p> 

Step 1: a rate cache with one upstream call per base

Rates come from AllRatesToday, which returns live mid-market rates for 160+ currencies. You can get a free API key and put it in ALLRATES_API_KEY.

The rates endpoint takes one base and a comma-separated list of targets. Many targets in one call count as one request, so we fetch all supported currencies at once. The response is always a JSON array, even for a single pair.

// lib/rates.js const API_URL = 'https://allratestoday.com/api/v1/rates'; const TTL_MS = 10 * 60 * 1000; // rates refresh about every 60 s; 10 min is fine for display const cache = new Map(); // base -> { rates, fetchedAt } const inflight = new Map(); // base -> Promise, so concurrent requests share one fetch async function fetchRates(base, targets) { const url = new URL(API_URL); url.searchParams.set('source', base); url.searchParams.set('target', targets.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: invalid or missing API key'); if (res.status === 429) throw new Error('Rates API: quota exceeded or rate limited'); if (!res.ok) throw new Error(`Rates API: HTTP ${res.status}`); const rows = await res.json(); // [{ rate, source, target, time }, ...] const rates = { [base]: 1 }; for (const row of rows) rates[row.target] = row.rate; return rates; } export async function getRates(base, targets) { const hit = cache.get(base); if (hit && Date.now() - hit.fetchedAt < TTL_MS) return hit.rates; if (inflight.has(base)) return inflight.get(base); const promise = fetchRates(base, targets) .then((rates) => { cache.set(base, { rates, fetchedAt: Date.now() }); return rates; }) .catch((err) => { if (hit) { // Keep serving the last good rates instead of breaking every page. console.warn(`${err.message}; serving rates from ${new Date(hit.fetchedAt).toISOString()}`); return hit.rates; } throw err; }) .finally(() => inflight.delete(base)); inflight.set(base, promise); return promise; } 

Two details matter here:

  1. The inflight map. When the cache expires under load, 50 requests can arrive in the same second. Without it, all 50 call the API. With it, they all await the same promise.
  2. Stale fallback. On a 401, 429 or timeout we return the previous rates if we have any. Old-by-15-minutes is much better than a 500 page.

Step 2: decide the currency for each request

Order of preference: an explicit ?currency= query, then a cookie the visitor set earlier, then the base currency. Only accept codes from an allowlist so nobody can pass arbitrary strings into Intl.NumberFormat.

// lib/pick-currency.js export function pickCurrency(req, supported, fallback) { const fromQuery = String(req.query.currency ?? '').toUpperCase(); if (supported.includes(fromQuery)) return { code: fromQuery, fromQuery: true }; const fromCookie = String(req.cookies?.currency ?? '').toUpperCase(); if (supported.includes(fromCookie)) return { code: fromCookie, fromQuery: false }; return { code: fallback, fromQuery: false }; } 

Step 3: the middleware

// middleware/currency.js import { getRates } from '../lib/rates.js'; import { pickCurrency } from '../lib/pick-currency.js'; const LOCALES = { USD: 'en-US', EUR: 'de-DE', GBP: 'en-GB', JPY: 'ja-JP', CAD: 'en-CA', AUD: 'en-AU', INR: 'en-IN', }; const formatters = new Map(); function formatterFor(currency) { if (!formatters.has(currency)) { formatters.set( currency, new Intl.NumberFormat(LOCALES[currency] ?? 'en-US', { style: 'currency', currency }), ); } return formatters.get(currency); } export function currency({ base = 'USD', supported = Object.keys(LOCALES) } = {}) { const targets = supported.filter((c) => c !== base); return async function currencyMiddleware(req, res, next) { const choice = pickCurrency(req, supported, base); let rates = null; try { rates = await getRates(base, targets); } catch (err) { console.error(err.message); // no rates at all yet: fall back to base prices } const code = rates?.[choice.code] ? choice.code : base; const rate = code === base ? 1 : rates[code]; const fmt = formatterFor(code); if (choice.fromQuery) { res.cookie('currency', code, { maxAge: 365 * 24 * 3600 * 1000, sameSite: 'lax' }); } res.locals.currency = code; res.locals.convert = (amount) => amount * rate; res.locals.price = (amount) => fmt.format(amount * rate); next(); }; } 

Intl.NumberFormat knows that JPY has no decimals and that de-DE puts the euro sign after the number. Formatters are cached because constructing them on every call is slow compared to format().

If the rate API has never answered (cold start plus outage), the page still renders in USD. That is the right failure mode for a storefront.

Step 4: wire it up

// app.js import express from 'express'; import cookieParser from 'cookie-parser'; import { currency } from './middleware/currency.js'; const app = express(); app.set('view engine', 'ejs'); app.use(cookieParser()); app.use(currency({ base: 'USD', supported: ['USD', 'EUR', 'GBP', 'JPY', 'CAD'] })); const products = [ { id: 1, name: 'Starter plan', priceUsd: 19 }, { id: 2, name: 'Team plan', priceUsd: 49 }, ]; // Server-rendered page: templates read res.locals directly app.get('/pricing', (req, res) => { res.render('pricing', { products }); }); // JSON route: same helper, no duplicated conversion code app.get('/api/products', (req, res) => { res.json({ currency: res.locals.currency, products: products.map((p) => ({ ...p, price: Math.round(res.locals.convert(p.priceUsd) * 100) / 100, priceFormatted: res.locals.price(p.priceUsd), })), }); }); app.listen(8080); 

And the view:

<!-- views/pricing.ejs --> <form method="get"> <select name="currency" onchange="this.form.submit()"> <% for (const c of ['USD','EUR','GBP','JPY','CAD']) { %> <option value="<%= c %>" <%= c === currency ? 'selected' : '' %>><%= c %></option> <% } %> </select> </form> <% for (const p of products) { %> <h2><%= p.name %></h2> <p><%= price(p.priceUsd) %> / month</p> <% } %> 

The <form method="get"> works with no client-side JavaScript framework. Selecting a currency reloads the page with ?currency=EUR, the middleware stores the cookie, and later pages remember the choice.

Note on rounding: for JPY the Math.round(... * 100) / 100 in the JSON route is harmless because the formatter drops decimals anyway, but if you store converted amounts, round to each currency's minor unit.

Only run it where you need it

Running the middleware on static assets is wasted work. Mount it on the routers that render prices:

const shop = express.Router(); shop.use(currency()); shop.get('/pricing', /* ... */); app.use('/', shop); 

Because of the cache, the cost per request is a Map lookup. The upstream API is called at most once per 10 minutes per base currency.

Multiple instances

The in-memory cache is per process. With 4 Node processes you make up to 4 upstream calls per TTL window, which is fine. If you run dozens of instances or serverless functions, move the cache to Redis or your platform's KV store. The caching guide compares the options.

Showing the rate time

The API returns a time field per row. If you sell to businesses, keep it in the cache entry and show "Prices converted at live mid-market rates, updated 10:15 UTC" near the total. It answers the "why did my price change?" support ticket before it is written. Field names are listed in the API reference.

FAQ

Should I charge in the converted currency?
This middleware is for display. If your payment provider charges in USD, label converted prices as approximate. If you charge in local currency, store the rate used at checkout with the order.

Why not call the API from the browser?
The keyed API sends no CORS headers, and your API key must stay on the server. Server-side conversion also means search engines and users without JavaScript see the right price.

Is 10 minutes too long a cache?
For product pages, no. Mid-market rates for major pairs rarely move more than a fraction of a percent in 10 minutes. Use a shorter TTL only for checkout totals.

Does this work with Express 4?
Yes, with one change: Express 4 does not catch rejected promises from async middleware. Our middleware already catches its own errors, so it works as written.