Generate a UUID in JavaScript
Learn how to generate, format, parse, and validate RFC 4122/9562 UUIDs in JavaScript using native Web Crypto and npm packages.
Universally Unique Identifiers (UUIDs) are 128-bit identifiers designed to provide high uniqueness guarantees without central coordination. In modern JavaScript environments (browsers, Node.js, Deno, Bun, and Cloudflare Workers), generating and validating UUIDs can be accomplished natively or using specialized utility packages.
Quick Start#
In modern JavaScript environments, the global crypto API provides native, zero-dependency UUID v4 generation:
The native crypto.randomUUID() method utilizes the underlying operating system cryptographically secure pseudorandom number generator (CSPRNG), providing high-entropy random identifiers compliant with RFC 4122 and RFC 9562.
Generating UUIDs with the uuid Package#
For projects requiring time-ordered identifiers (UUID v7), namespace hashing (UUID v5), or backward compatibility with older runtimes, the official uuid package is the standard:
Parsing a UUID into Binary Bytes#
A canonical UUID string is 36 characters long, consisting of 32 hexadecimal digits and 4 hyphens. When persisting identifiers to databases or compact binary protocols, you can parse the string into a 16-byte Uint8Array:
Validating a UUID#
Validating incoming identifiers prevents malformed database records and rejects invalid formats early. Note that format validation checks structure only; you must always combine format checks with parameterized queries and contextual output handling to prevent injection:
If you prefer a zero-dependency validation regex:
UUID v4 vs UUID v7 in JavaScript#
- UUID v4: Purely random. Excellent for distributed tokens, session cookies, and public non-indexed references. However, random values cause index fragmentation in B-tree database indexes.
- UUID v7: Time-ordered. Encodes an epoch millisecond timestamp in the leading 48 bits, providing chronological sorting while retaining random entropy. Monotonic ordering across multiple UUIDs generated within the exact same millisecond requires an implementation-specific counter or stateful increment strategy (RFC 9562 Section 6.2). Preferred for database primary keys.
Best Practices#
- Use
crypto.randomUUID()for standard v4: If you only need random identifiers in modern runtimes, avoid adding external bundle weight. - Never use
Math.random():Math.random()lacks cryptographic entropy and is predictable. - Case Sensitivity: UUID text is case-insensitive. RFC 9562 permits uppercase, lowercase, or mixed case on input, though lowercase is conventional for normalized outputs.