Developer Documentation
JavaScript
Updated September 18, 2026

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:

JavaScript
1// Native modern JavaScript (Node.js 14.17+, modern browsers, Bun, Deno)2const uuid = crypto.randomUUID();34console.log(uuid);5// Output: "36b8f84d-df4e-4d49-b662-bcde71a8764f"

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:

Bash
1npm install uuid
JavaScript
1import { v4 as uuidv4, v7 as uuidv7 } from "uuid";23// Standard random UUIDv44const randomId = uuidv4();5console.log("v4:", randomId);67// Time-ordered UUIDv7 (ideal for database primary keys)8const timeOrderedId = uuidv7();9console.log("v7:", timeOrderedId);

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:

JavaScript
1import { parse as parseUuid, stringify as stringifyUuid } from "uuid";23const uuidStr = "710b962e-041c-11e1-9234-0123456789ab";45// Parse canonical string into a 16-byte Uint8Array6const bytes = parseUuid(uuidStr);7console.log("Byte length:", bytes.length); // 1689// Convert bytes back to canonical hyphenated string10const reconstructed = stringifyUuid(bytes);11console.log("Reconstructed:", reconstructed === uuidStr); // true

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:

JavaScript
1import { validate as validateUuid, version as uuidVersion } from "uuid";23const input = "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d";45if (validateUuid(input)) {6  console.log("Valid UUID, version:", uuidVersion(input));7} else {8  console.error("Invalid UUID string provided");9}

If you prefer a zero-dependency validation regex:

JavaScript
1function isValidUUID(str) {2  const uuidRegex = /^[--f]{}-[--f]{}-[-][--f]{}-[][--f]{}-[--f]{}$/i;3  return typeof str === "string" && uuidRegex.test(str);4}

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#

  1. Use crypto.randomUUID() for standard v4: If you only need random identifiers in modern runtimes, avoid adding external bundle weight.
  2. Never use Math.random(): Math.random() lacks cryptographic entropy and is predictable.
  3. Case Sensitivity: UUID text is case-insensitive. RFC 9562 permits uppercase, lowercase, or mixed case on input, though lowercase is conventional for normalized outputs.

References#

Implement UUID in other languages: