How to generate secure UUIDs
August 2, 2026 · 12 min read
A secure UUID uses unpredictable random bits from a CSPRNG and sets RFC 4122 version and variant fields correctly. Insecure IDs come from Math.random, predictable seeds, or truncated hashes - fine for UI keys, dangerous for session or row identifiers.
What secure means
Attackers should not guess the next ID. That requires enough entropy (122 random bits in v4) and no central leak of previously issued values. Collision probability is astronomically low; brute force is the practical threat if entropy is weak.
Generate UUID v4
// Browser and Node 19+
const id = crypto.randomUUID();
// Python
import uuid
print(uuid.uuid4())
When to use UUID v7
UUID v7 embeds a millisecond timestamp in the high bits plus randomness. Use it for database primary keys when you want roughly time-ordered inserts without a separate created_at index column. Fall back to v4 when v7 is unavailable in your runtime.
Browser generator
The UUID generator uses Web Crypto in the browser for one-off IDs, bulk generation, and copy-friendly formats. Validate downstream with the UUID validator when ingesting partner data.
Production checklist
- Never use Math.random for security-sensitive IDs.
- Store UUIDs as binary or char(36) consistently - avoid mixed string formats in one table.
- Document whether APIs expose lowercase canonical form only.
FAQ
- Is UUID v4 secure enough for session tokens?
- Entropy is sufficient, but sessions also need expiry, rotation, and server-side revocation - UUID alone is not a session system.
- Can two clients generate the same UUID?
- Theoretically yes (collision); practically no for v4 with proper RNG.
Related: Best UUID generators · UUID generator