Why You Should Use crypto.randomUUID() Instead of Math.random() for IDs
Math.random() is not random enough for IDs. Here's why — and what to use instead.
The Problem with Math.random()
Math.random() is a pseudo-random number generator (PRNG). It's deterministic: given the same seed, it produces the same sequence. The seed is usually the current timestamp.
This means:
- If two tabs initialize at the same millisecond, they can produce the same "random" values
- The sequence is predictable once you know the seed
- It's not suitable for security-sensitive IDs
crypto.randomUUID()
Available in all modern browsers and Node.js 14.17+:
const id = crypto.randomUUID();
// "550e8400-e29b-41d4-a716-446655440000"
This generates a v4 UUID using the operating system's cryptographically secure random number generator (CSPRNG) — the same source used for cryptographic keys.
Generating Multiple UUIDs
function generateUUIDs(count, options = {}) {
const { uppercase = false, stripHyphens = false } = options;
return Array.from({ length: count }, () => {
let id = crypto.randomUUID();
if (stripHyphens) id = id.replace(/-/g, '');
if (uppercase) id = id.toUpperCase();
return id;
});
}
UUID v4 Structure
A UUID looks random but has structure:
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
^ ^
| y is 8, 9, a, or b (variant bits)
version (always 4 for v4)
The version and variant bits take up 6 of the 128 bits, leaving 122 bits of actual randomness. That's 2^122 possible values — collision probability is negligible.
Collision Probability
Generating 1 billion UUIDs per second, you'd expect your first collision after about 85 years. For practical applications, UUIDs are safe to generate independently without coordination.
When You Still Need a Server
UUIDs are great for client-generated IDs, but if you need sequential IDs (for database pagination), time-ordered IDs (UUIDv7), or guaranteed global uniqueness across distributed systems, the server is still the right place.
Generate UUIDs at toolzip.app/tools/uuid-generator.
Top comments (0)