logo hsb.horse
← Back to snippets index

Snippets

Polyfill for crypto.randomUUID

A polyfill implementation of the crypto.randomUUID function. While all browsers now support this, it serves as a useful reference for understanding how UUID v4 works.

Published: Updated:

All browsers now support crypto.randomUUID, so there’s no need to implement this polyfill anymore. However, it makes for a good exercise in understanding how UUID v4 works.

Code

type UUID = `${string}-${string}-${string}-${string}-${string}`;
const FN_NAME = "randomUUID";
const BASE_STR = [1e7, 1e3, 4e3, 8e3, 1e11].join("-");
/**
* Generate UUID v4
* Falls back to polyfill if browser doesn't support randomUUID
*/
export function randomUUID(): UUID {
const api = crypto;
if (FN_NAME in api) return api[FN_NAME]();
return BASE_STR.replace(/[018]/g, replacer) as UUID;
}
function replacer(char: string): string {
const random = crypto.getRandomValues(new Uint8Array(1))[0];
const int = Number.parseInt(char);
return (int ^ (random & (15 >> (int / 4)))).toString(16);
}

How UUID v4 Works

UUID v4 is a randomly generated 128-bit identifier. The standard format is 8-4-4-4-12, totaling 36 characters including hyphens.

  • xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  • The 13th character is always 4 (indicates version)
  • The 17th character is 8, 9, a, or b (indicates variant)

Implementation Breakdown

BASE_STR becomes the template “10000000-1000-4000-8000-100000000000”. UUID generation works by replacing characters 0, 1, and 8 with random values via replace().

crypto.getRandomValues provides cryptographically secure random numbers, and bit operations embed these into each position of the UUID.

Notes

  • Use native crypto.randomUUID in production code
  • This implementation is for educational purposes
  • Performance is inferior to native implementation