Checkout on a car rental site worked on my laptop and crashed on my phone. Same code, same network, same dev server. The error:
TypeError: crypto.randomUUID is not a function
Why it only broke on the phone
On the laptop I opened the site at http://localhost:3000. On the phone I opened it by the laptop's LAN address, something like http://192.168.1.20:3000.
crypto.randomUUID() is only available in a secure context. In practice that means pages served over HTTPS, plus local addresses browsers treat as trustworthy, such as http://localhost and http://127.0.0.1. A plain-HTTP LAN address like 192.168.1.20 is neither, so the browser doesn't define the function there. crypto.getRandomValues() still works in insecure contexts, but randomUUID() and the whole of crypto.subtle don't.
Checkout called it the moment the page loaded, to create an idempotency key: a random id sent with the booking request, so that a double tap or a retry can't create two bookings.
const [idempotencyKey] = useState(() => crypto.randomUUID());
The fix
crypto.getRandomValues() is available everywhere, and a version-4 UUID is just 16 random bytes with a few bits set. So a tiny helper uses randomUUID when it exists and builds the same thing by hand when it doesn't:
/** A random v4 UUID. crypto.randomUUID exists only on HTTPS and localhost. */
export function uuid(): string {
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
const b = crypto.getRandomValues(new Uint8Array(16));
b[6] = (b[6] & 0x0f) | 0x40; // version 4
b[8] = (b[8] & 0x3f) | 0x80; // RFC 4122 variant
const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
}
Checkout and the corporate booking form both use uuid() now, and the phone test works.
Is this only a dev problem?
Mostly, because production runs on HTTPS. But "mostly" covers a few real cases: staging servers without TLS, internal tools on an office network, kiosks and embedded browsers. The fallback costs a dozen lines, so it stays.
What I took away
- Test on a real phone, over the network, early.
localhostis a secure context, which hides a whole class of bugs. - Know which APIs need a secure context.
crypto.randomUUID, the clipboard API, service workers, geolocation and camera access all behave differently on plain HTTP. - Idempotency is a client–server contract. The client generates the key once, when the form loads, and resends it with every retry. The server does the real work: it stores the key scoped to the customer, together with the request and its result, and returns that stored result for a repeat instead of creating a second booking. The key on its own makes nothing safe.
- #Frontend
- #Web Platform