How to Generate UUID v4: Web Crypto API, Node.js, Python, SQL, and Strict Regex Validation
Complete developer guide to generating cryptographically secure version 4 UUIDs. Learn native generation using Web Crypto crypto.randomUUID(), backend patterns in Python/Go/Rust/SQL, and strict RFC 4122 regex validation.
Version 4 Universally Unique Identifiers (UUID v4) are 128-bit identifiers constructed using cryptographically secure pseudorandom numbers. They are the industry standard for distributed primary keys, transaction tracing, and idempotent request tokens because they require no central coordinator or registration authority to guarantee uniqueness.
The CSPRNG Rule Why Math random Must Never Be Used
A standard UUID v4 contains 122 bits of entropy. Many legacy tutorials generated UUIDs by stringing together Math.random().toString(16) calls. This is dangerous in production systems:
- Math.random() is not cryptographically secure. It uses predictable pseudo-random algorithms (such as xoshiro128+) that can be reverse-engineered from a small sequence of observed IDs.
- Under high concurrency (e.g. parallel worker threads or serverless invocations seeded with the same system clock state), Math.random() produces catastrophic duplicate key collisions.
- Always use a Cryptographically Secure Pseudorandom Number Generator (CSPRNG) backed by OS entropy (/dev/urandom on Unix-like platforms or BCryptGenRandom on Windows).
Native Browser and Node js Generation with crypto randomUUID
All modern browsers (Chrome 92+, Safari 15.4+, Firefox 95+) and Node.js (v14.17+) support native UUID v4 generation through the standard Web Crypto API without requiring third-party libraries like uuid:
// Native modern generation in Browser & Node.js
const id = crypto.randomUUID();
console.log(id); // "7b39a8a1-5f2c-4c6e-8d4e-123456789abc"
// Secure fallback for legacy environments using crypto.getRandomValues()
function generateSecureUUID() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
// Set version to 0100 (v4) at byte 6
bytes[6] = (bytes[6] & 0x0f) | 0x40;
// Set variant to 10xx (RFC 4122) at byte 8
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}Backend Code Recipes Python Go Rust Java
Standard library and ecosystem patterns for generating UUIDv4 across backend runtimes:
# Python 3 (Standard Library)
import uuid
unique_id = str(uuid.uuid4())
print(unique_id) # "c9a646d3-9c61-4cd9-bc15-47044d6fb330"// Go (using github.com/google/uuid)
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
newID := uuid.NewString()
fmt.Println(newID) // "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
}Database Native Generation Postgres MySQL SQLite
Generating UUIDs directly inside database defaults eliminates roundtrip overhead for insert queries:
-- PostgreSQL 13+ (built-in without pgcrypto)
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_email VARCHAR(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- MySQL 8.0+
CREATE TABLE orders (
id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1)),
customer_email VARCHAR(255) NOT NULL
);
-- SQLite (using custom random blob format or application-level ID)
CREATE TABLE orders (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab', 1 + (abs(random()) % 4), 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))
);Strict RFC 4122 UUID v4 Regex Validation
Many generic UUID regular expressions only check character length and hyphens. A strict UUID v4 validator must verify that the version digit is '4' and the variant nibble is '8', '9', 'a', or 'b':
// Strict RFC 4122 Version 4 UUID Regex
const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isValidUUIDv4(str) {
return typeof str === "string" && UUID_V4_REGEX.test(str);
}
console.log(isValidUUIDv4("f47ac10b-58cc-4372-a567-0e02b2c3d479")); // true
console.log(isValidUUIDv4("f47ac10b-58cc-1372-a567-0e02b2c3d479")); // false (version is 1, not 4)
console.log(isValidUUIDv4("f47ac10b-58cc-4372-7567-0e02b2c3d479")); // false (variant is 7, not 8/9/a/b)Inspecting UUIDv4 Bit Fields and Entropy Layout
Every 36-character canonical UUIDv4 string (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479) embeds exact structural flags within its 128-bit payload:
| Hex Segment | Example Value | Fixed vs. Random Bits | Bit Allocation & Meaning |
|---|---|---|---|
| Segment 1 (time_low) | f47ac10b | 32 bits (100% random) | Random 4-byte high-entropy block |
| Segment 2 (time_mid) | 58cc | 16 bits (100% random) | Random 2-byte entropy block |
| Segment 3 (time_hi_and_version) | 4372 | 4 fixed bits ('4') + 12 random bits | Leading nibble 0100 indicates RFC 4122 Version 4 |
| Segment 4 (clock_seq_and_variant) | a567 | 2 fixed bits ('10') + 14 random bits | Leading bits 10xx dictate variant (hex 8, 9, a, or b) |
| Segment 5 (node) | 0e02b2c3d479 | 48 bits (100% random) | Random 6-byte tail sequence |
When Not to Use UUIDv4 Database Clustered Keys and Short IDs
While UUIDv4 is optimal for distributed event IDs and uncoordinated security tokens, applying it indiscriminately introduces two major performance pitfalls:
- B-Tree Clustered Index Thrashing: Because UUIDv4 values are completely random, database inserts hit arbitrary leaves across the B-Tree index. This causes continuous page splits and heavy random disk I/O once table size exceeds memory buffer cache. For database primary keys, time-ordered UUIDv7 (RFC 9562) or ULID is strongly recommended.
- User-Facing Link & SMS Bloat: A 36-character hyphenated UUID is unnecessarily long for customer URLs, SMS codes, or verification tokens. A compact 21-character NanoID or 10-character Base62 string provides equivalent practical uniqueness with significantly better readability.
For detailed analysis of index fragmentation and UUID version trade-offs, explore our architectural guide on Understanding UUIDs or compare identifier systems in UUID vs. GUID vs. ULID.
[NEED: real detail on CoShareX UUID generator throughput or feature limits — e.g., batch generation of up to 10,000 UUIDs in a single click with uppercase/lowercase and hyphen options in client Web Worker].
Code Formatter & Converter Suite
Validate, format, minify, and convert JSON, SQL, YAML, XML, and code dialects directly on your local machine.
Frequently Asked Questions
How do I generate a UUID in JavaScript without third-party npm packages?
In modern browsers and Node.js 14.17+, use the native standard Web Crypto API call: crypto.randomUUID(). It is faster than third-party packages and cryptographically secure.
What is the regex to validate a strict UUID v4?
Use the strict RFC 4122 pattern: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. This ensures the 13th character is always '4' (version) and the 17th character is '8', '9', 'a', or 'b' (variant).
Is crypto.randomUUID() cryptographically secure?
Yes. crypto.randomUUID() uses the underlying operating system's cryptographically secure entropy source (such as /dev/urandom on Unix-like platforms or CryptGenRandom/BCryptGenRandom on Windows), ensuring unpredictable values suitable for security tokens.
Conclusion
Leverage native crypto.randomUUID() in web runtimes and database-level gen_random_uuid() defaults to generate collision-resistant, secure identifiers without runtime dependencies.
Related Articles
Understanding UUIDs: Architecture, RFC 4122 vs RFC 9562, Collision Math, and Index Performance
Architectural guide to Universally Unique Identifiers (UUID). Explore bit-level structure, compare UUID v1 through v7, analyze B-tree index fragmentation, and calculate real collision probabilities.
ArchitectureUUID vs GUID vs ULID vs NanoID: Choosing the Right Identifier in 2026
Compare modern unique identifiers: UUID v4 vs Microsoft GUID vs ULID vs NanoID vs UUID v7. Entropy, sortability, database B-Tree clustering, and URL safety.