RandomUUID Generates Unpredictable V4 IDs
crypto.randomUUID produces RFC 4122 v4 identifiers with 122 random bits, version and variant nibbles fixed by the spec at known positions.
Code
// crypto.randomUUID 生成 RFC 4122 v4:版本位固定 4,变体位限 8/9/a/b
const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const ids = Array.from({ length: 3 }, () => crypto.randomUUID());
console.log('all v4-shaped:', ids.every((id) => V4.test(id)));
// 122 位随机量:一万次抽取碰撞概率可忽略,可直接当主键用
const unique = new Set(Array.from({ length: 10_000 }, () => crypto.randomUUID()));
console.log('10k draws, all distinct:', unique.size === 10_000);
// 版本与变体位在规范位置,不是随机结果
const sample = ids[0];
console.log('version nibble:', sample[14]);
console.log('variant nibble:', sample[19]);
// 只在安全上下文(HTTPS/localhost)可用,降级方案需要另行提供
console.log('available:', typeof crypto.randomUUID === 'function');Output
Captured from a sandboxed run of this snippet in the build pipeline.
all v4-shaped: true
10k draws, all distinct: true
version nibble: 4
variant nibble: 9
available: trueSpec-shaped output
The V4 regex pins the fixed positions: version nibble 4 at index 14 and variant nibble in [89ab] at index 19. Three draws all pass, printed as all v4-shaped: true — the format is guaranteed by the spec, not coincidence.
Randomness you can key on
122 of the 128 bits are random. Ten thousand draws land in a Set with size 10000 (10k draws, all distinct: true), which is why v4 UUIDs are usable as primary keys without a central allocator.
Context requirement
crypto.randomUUID exists only in secure contexts (HTTPS or localhost). The demo prints available: true in such a context; elsewhere the call must be guarded or replaced with a fallback source.
Interactive Tools for This Topic
FAQ
- Why are version and variant nibbles fixed?
- RFC 4122 reserves them: index 14 encodes the version (4) and index 19 the variant, so consumers can identify the format without inspecting the random bits.
- How much randomness does a v4 UUID carry?
- 122 of the 128 bits; the six spec bits (version and variant) are fixed, which still makes collisions negligible for keying purposes.
Report a problem with this exampleOpens a pre-filled issue on GitHub.