Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): currency detection utilities and public /api/currency endpoint

Richie McIlroy5434801c0259
diff --git a/apps/web/__tests__/unit/currency.test.ts b/apps/web/__tests__/unit/currency.test.ts
new file mode 100644
index 000000000..1dd036986
--- /dev/null
+++ b/apps/web/__tests__/unit/currency.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+import {
+ currencyForCountry,
+ currencySymbol,
+ formatAmount,
+ SUPPORTED_CURRENCIES,
+} from "@/utils/currency";
+
+describe("currencyForCountry", () => {
+ it("maps the UK and crown dependencies to GBP", () => {
+ for (const country of ["GB", "IM", "JE", "GG"]) {
+ expect(currencyForCountry(country)).toBe("gbp");
+ }
+ });
+
+ it("maps eurozone countries and territories to EUR", () => {
+ for (const country of ["DE", "FR", "IE", "NL", "GF", "YT", "XK"]) {
+ expect(currencyForCountry(country)).toBe("eur");
+ }
+ });
+
+ it("falls back to USD for non-euro EU countries", () => {
+ for (const country of ["SE", "PL", "DK", "CZ", "HU", "NO", "CH"]) {
+ expect(currencyForCountry(country)).toBe("usd");
+ }
+ });
+
+ it("falls back to USD for the rest of the world", () => {
+ for (const country of ["US", "CA", "AU", "IN", "BR", "JP"]) {
+ expect(currencyForCountry(country)).toBe("usd");
+ }
+ });
+
+ it("falls back to USD when the country is missing or empty", () => {
+ expect(currencyForCountry(null)).toBe("usd");
+ expect(currencyForCountry(undefined)).toBe("usd");
+ expect(currencyForCountry("")).toBe("usd");
+ });
+
+ it("normalizes casing and surrounding whitespace", () => {
+ expect(currencyForCountry("gb")).toBe("gbp");
+ expect(currencyForCountry(" de ")).toBe("eur");
+ });
+
+ it("only ever returns a supported currency", () => {
+ for (const country of ["GB", "DE", "US", "ZZ", null]) {
+ expect(SUPPORTED_CURRENCIES).toContain(currencyForCountry(country));
+ }
+ });
+});
+
+describe("currencySymbol", () => {
+ it("returns the symbol for each supported currency", () => {
+ expect(currencySymbol("usd")).toBe("$");
+ expect(currencySymbol("gbp")).toBe("£");
+ expect(currencySymbol("eur")).toBe("€");
+ });
+
+ it("accepts uppercase codes", () => {
+ expect(currencySymbol("GBP")).toBe("£");
+ });
+
+ it("falls back to an uppercase code prefix for other currencies", () => {
+ expect(currencySymbol("aud")).toBe("AUD ");
+ expect(currencySymbol("jpy")).toBe("JPY ");
+ });
+});
+
+describe("formatAmount", () => {
+ it("formats supported currencies with their symbol", () => {
+ expect(formatAmount(12, "usd")).toBe("$12.00");
+ expect(formatAmount(12, "gbp")).toBe("£12.00");
+ expect(formatAmount(12, "eur")).toBe("€12.00");
+ });
+
+ it("keeps parity pricing identical apart from the symbol", () => {
+ const amounts = SUPPORTED_CURRENCIES.map((currency) =>
+ formatAmount(8.16, currency).replace(/^\D+/, ""),
+ );
+ expect(new Set(amounts)).toEqual(new Set(["8.16"]));
+ });
+
+ it("formats currencies outside the supported set", () => {
+ expect(formatAmount(12, "aud")).toContain("12.00");
+ });
+
+ it("falls back without throwing on an invalid currency code", () => {
+ expect(formatAmount(12, "notacurrency")).toBe("NOTACURRENCY 12.00");
+ });
+});
diff --git a/apps/web/app/api/currency/route.ts b/apps/web/app/api/currency/route.ts
new file mode 100644
index 000000000..cfd8fa086
--- /dev/null
+++ b/apps/web/app/api/currency/route.ts
@@ -0,0 +1,21 @@
+import type { NextRequest } from "next/server";
+import { currencyForCountry } from "@/utils/currency";
+
+export const dynamic = "force-dynamic";
+
+export async function GET(request: NextRequest) {
+ const override =
+ process.env.VERCEL_ENV !== "production"
+ ? request.nextUrl.searchParams.get("country")
+ : null;
+ const country = override || request.headers.get("x-vercel-ip-country");
+
+ return Response.json(
+ { currency: currencyForCountry(country), country: country ?? null },
+ {
+ // The response varies per visitor IP, so it must never land in a shared
+ // CDN cache where one region's currency would be served to another.
+ headers: { "Cache-Control": "private, no-store" },
+ },
+ );
+}
diff --git a/apps/web/hooks/useCurrency.ts b/apps/web/hooks/useCurrency.ts
new file mode 100644
index 000000000..a1adf84a0
--- /dev/null
+++ b/apps/web/hooks/useCurrency.ts
@@ -0,0 +1,42 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import {
+ currencySymbol,
+ isSupportedCurrency,
+ type SupportedCurrency,
+} from "@/utils/currency";
+
+let currencyRequest: Promise<SupportedCurrency> | null = null;
+
+function loadCurrency(): Promise<SupportedCurrency> {
+ currencyRequest ??= fetch("/api/currency")
+ .then((res) => res.json())
+ .then((data: { currency?: string }) =>
+ isSupportedCurrency(data.currency) ? data.currency : "usd",
+ )
+ .catch((): SupportedCurrency => {
+ currencyRequest = null;
+ return "usd";
+ });
+
+ return currencyRequest;
+}
+
+export function useCurrency() {
+ // Starts at usd so SSR and the first client render agree; geo detection only
+ // ever runs in the effect below.
+ const [currency, setCurrency] = useState<SupportedCurrency>("usd");
+
+ useEffect(() => {
+ let active = true;
+ loadCurrency().then((next) => {
+ if (active) setCurrency(next);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ return { currency, symbol: currencySymbol(currency) };
+}
diff --git a/apps/web/utils/currency.ts b/apps/web/utils/currency.ts
new file mode 100644
index 000000000..1c639d234
--- /dev/null
+++ b/apps/web/utils/currency.ts
@@ -0,0 +1,88 @@
+export const SUPPORTED_CURRENCIES = ["usd", "gbp", "eur"] as const;
+
+export type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number];
+
+const GBP_COUNTRIES = new Set(["GB", "IM", "JE", "GG"]);
+
+// Mirrors the countries Stripe Checkout's IP localization presents in EUR, so
+// the displayed price matches what checkout charges. Non-euro EU countries
+// (SE, PL, DK, ...) are deliberately absent and fall through to USD.
+const EUR_COUNTRIES = new Set([
+ "AD",
+ "AT",
+ "AX",
+ "BE",
+ "BL",
+ "CY",
+ "DE",
+ "EE",
+ "ES",
+ "FI",
+ "FR",
+ "GF",
+ "GP",
+ "GR",
+ "HR",
+ "IE",
+ "IT",
+ "LT",
+ "LU",
+ "LV",
+ "MC",
+ "ME",
+ "MF",
+ "MT",
+ "NL",
+ "PM",
+ "PT",
+ "RE",
+ "SI",
+ "SK",
+ "SM",
+ "TF",
+ "VA",
+ "XK",
+ "YT",
+]);
+
+const CURRENCY_SYMBOLS: Record<SupportedCurrency, string> = {
+ usd: "$",
+ gbp: "£",
+ eur: "€",
+};
+
+export function isSupportedCurrency(
+ value: string | null | undefined,
+): value is SupportedCurrency {
+ return SUPPORTED_CURRENCIES.includes(value as SupportedCurrency);
+}
+
+export function currencyForCountry(
+ country: string | null | undefined,
+): SupportedCurrency {
+ if (!country) return "usd";
+
+ const code = country.trim().toUpperCase();
+ if (GBP_COUNTRIES.has(code)) return "gbp";
+ if (EUR_COUNTRIES.has(code)) return "eur";
+ return "usd";
+}
+
+// Billing surfaces render whatever currency Stripe returns, which may be a code
+// we have no symbol for, so unknown codes degrade to a readable prefix.
+export function currencySymbol(code: string): string {
+ const normalized = code.toLowerCase();
+ if (isSupportedCurrency(normalized)) return CURRENCY_SYMBOLS[normalized];
+ return `${code.toUpperCase()} `;
+}
+
+export function formatAmount(amount: number, currency: string): string {
+ try {
+ return new Intl.NumberFormat("en", {
+ style: "currency",
+ currency,
+ }).format(amount);
+ } catch {
+ return `${currencySymbol(currency)}${amount.toFixed(2)}`;
+ }
+}