Generate a random UUID
Return a version 4 UUID from the platform’s cryptographic generator.
function uuid() { return crypto.randomUUID(); }
Usage
const key = uuid();
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(key); // → true
key.length; // → 36
Know the limits
- crypto.randomUUID() returns an RFC 9562 version 4 UUID. In browsers it requires a secure context: HTTPS or localhost.
- The original built UUIDs from Math.random, which is not a cryptographic generator.
- As an idempotency key, create the UUID once per operation and store it with the operation: a new UUID on every retry defeats deduplication. Oveyon accepts Idempotency-Key values of 1–190 characters; see Build an idempotency key.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Generate a random UUID from the original 1loc collection by Nguyen Huu Phuoc, with w3bdesign. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses crypto.randomUUID() instead of Math.random. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.