Dev.to WebDev 🛠 Dev 👁 2 📖 4 min read

Generating UUIDs in the Browser: One Line, 122 Random Bits

Subtitle: Most UUID snippets copied around the web are built on Math.random(). The browser ships a cryptographically secure generator built in — here is the one line, the maths behind it, and when version 4 is the wrong

Subtitle: Most UUID snippets copied around the web are built on Math.random(). The browser ships a cryptographically secure generator built in — here is the one line, the maths behind it, and when version 4 is the wrong choice.

Every app reaches the same moment: you need an ID for a new record, right now, on the client, without asking a server to mint one. Two phones creating records offline, a form generating a draft key, a test seeding a database — all need identifiers that will not collide when everything meets in one table.

The snippet most people copy for this is a clever-looking function built on Math.random(). The shape is right; the randomness is not. I built the UUID Generator on Toolenix on the browser’s own cryptographic generator instead. Here is how it works.

The core idea: the browser already has a secure generator

You do not need a library or a snippet. The Web Crypto API ships in every modern browser, and crypto.randomUUID() generates a version 4 UUID using a cryptographically secure random number generator:

const id = crypto.randomUUID();
// for example "66d71f65-5c65-4272-a661-2f89e6905883"

One call returns a 36-character string: 32 hexadecimal digits in five groups of 8-4-4-4-12, separated by hyphens. Try it in your console.

Reading the anatomy: where the randomness lives

A UUID is 128 bits, but six of them are fixed markers. In the example, the third group 4272 starts with 4 — version 4, the random version. The fourth group a661 starts with a, one of 8, 9, a, or b — the standard variant layout. So 128 − 6 = 122 bits are genuinely random: 2^122 possible values, about 5.3 × 10^36.

Collisions are a birthday-paradox question, and the maths is reassuring. Generate a billion UUIDs and the chance any two collide is roughly 1 in 10^19. You would need about 2.7 × 10^18 UUIDs before a collision becomes a coin flip — even at a billion a second, that takes about 86 years. Uniqueness is probabilistic, not guaranteed, but the probability is engineered to be irrelevant.

Why the copied snippet is a problem

MDN says it plainly about Math.random(): it "does not provide cryptographically secure random numbers. Do not use them for anything related to security." A Math.random() UUID looks identical to a real one, so the weakness stays invisible — until someone predicts IDs meant to be unguessable, like invite links built on them. crypto.randomUUID() costs one line and removes the question.

The part people actually need: generating in bulk

One UUID is a demo; seeding a database needs a list, in your stack’s format. This is the tool’s actual logic — a loop plus two string transforms:

function generateUuids(count, fmt) {
  const list = [];
  for (let i = 0; i < count; i++) {
    let id = crypto.randomUUID();
    if (fmt === "hyphen-upper") id = id.toUpperCase();
    if (fmt === "no-hyphen") id = id.replace(/-/g, "");
    list.push(id);
  }
  return list;
}

The no-hyphen form is 32 characters — the same 128 bits, separators removed. Case is cosmetic to the value but not always to storage: a Postgres uuid column accepts either case and always outputs lowercase, while a text column compares strings, so mixed case can split one ID across two rows. Pick lowercase, the standard output form, and stay consistent.

Building one by hand: the fallback

Where randomUUID() is missing, build the same version 4 UUID from raw secure bytes — sixteen random bytes, two bit-masks, then hex formatting:

function uuidV4Fallback() {
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx
  const hex = [...bytes]
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

bytes[6] gets its top nibble forced to 0100 (version 4), bytes[8] its top two bits forced to 10 (the standard variant) — the six fixed bits from the anatomy above. Everything else stays random.

The details that make it feel like a real tool

  • Bulk generation — up to 100 UUIDs at a time, because nobody seeds a table one ID at a time.
  • Three formats — lowercase with hyphens (default), UPPERCASE, or 32 characters with no hyphens.
  • Copy in one click — a Copy All button puts the whole list on your clipboard, ready for a seed file.
  • Ready on load — a first set is generated as the page opens.
  • Private by construction — no server endpoint to call; the randomness comes from your own browser.

The honest limits

crypto.randomUUID() only exists in secure contexts — HTTPS or localhost — so a plain-HTTP page cannot use it. That is the right failure mode.

Version 4 is also wrong when IDs must sort by creation time, because random keys scatter inserts across a database index instead of appending neatly. That is what version 7 is for: standardised in RFC 9562 (May 2024, which replaced RFC 4122), it puts a 48-bit millisecond timestamp in the leading bits so IDs sort in creation order — at the cost of revealing when each ID was created. A v4 ID reveals nothing. Choose v4 when the ID must say nothing, v7 when it must sort.

And a UUID is an identifier, not a secret. IDs end up in URLs, logs, and support tickets. If something must stay secret, generate it as a token and store it hashed; do not lean on an ID’s randomness for security it was never asked to provide.

Why client-side wins for tools like this

  • No coordination: any device mints IDs offline, and they merge later with no central register.
  • Speed: no round-trip, no rate limit — a hundred UUIDs take a fraction of a millisecond.
  • Cost: static hosting, no server to scale, no API bill for other people’s IDs.
  • Reliability: nothing to go down; if the page loads, the generator works, even offline after the first load.

Try it

The generator is live at toolenix.com/tools/uuid-generator — free, no sign-up, every ID minted in your browser. The whole site is built on the same idea: 113 tools, all client-side.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.