Generate UUID v4

Generate a random UUID v4 (Universally Unique Identifier) using the Web Crypto API.

Code

Utilities
crypto.randomUUID();
Browser·fetch() may be limited by CORS

What is UUID v4?

UUID v4 is purely random — 122 bits of randomness with 6 bits reserved for version and variant markers. This gives roughly 5.3 × 10³⁶ possible values.

f47ac10b-58cc-4372-a567-0e02b2c3d479 ↑ ↑ 4 8-b (version and variant bits)

When to Use UUID v4

Use CaseWhy v4 Works
Database primary keysSimple, no coordination needed
Session IDsUnpredictable, secure
API request IDsEasy to generate anywhere
Temporary identifiersNo meaning, just uniqueness

When NOT to Use UUID v4

ScenarioBetter Alternative
Need sortable IDsUse UUID v7 (timestamp-based)
Database index performance mattersUse UUID v7 (sequential)
Need deterministic IDsUse UUID v3/v5 (name-based)
Debugging with timestampsUse UUID v1 or v7

UUID v4 vs Auto-Increment IDs

UUID v4Auto-Increment
Generate anywhere (client, server, offline)Requires database roundtrip
No information leakageReveals record count
Harder to guessPredictable (id+1)
Larger storage (16 bytes vs 4-8)Smaller, faster indexes
Random = poor index localitySequential = good locality

Collision Probability

With 122 random bits, you'd need to generate 1 billion UUIDs per second for 86 years to have a 50% chance of one collision. In practice, collisions are not a concern.


More JavaScript Snippets