Skip to content
How to Generate UUID v4 in JavaScript

How to Generate UUID v4 in JavaScript

What Is a UUID v4?

A UUID (Universally Unique Identifier) is a 128-bit identifier designed to be globally unique without a central authority. The v4 variant generates UUIDs using random or pseudo-random numbers, making them ideal for distributed systems where coordination between nodes is impractical.

A UUID v4 looks like this: 550e8400-e29b-41d4-a716-446655440000. It follows the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where 4 indicates version 4 and y is one of 8, 9, a, or b.

Method 1: crypto.randomUUID()

The simplest and most modern approach in JavaScript is the built-in crypto.randomUUID() method, available in all modern browsers and Node.js 19+:

const id = crypto.randomUUID();
console.log(id); // "3b241101-e2bb-4d67-8b0d-7b0a5c9d2e1f"

This method is cryptographically secure, fast, and requires no dependencies. It is the recommended approach for most use cases in 2026.

Browser support: Chrome 92+, Firefox 95+, Safari 15.4+, Edge 92+. All modern browsers support it.

Node.js support: Available since Node.js 19 as a global. In Node.js 16-18, access it via require('crypto').randomUUID().

Method 2: Web Crypto API

If you need more control or want to understand how UUID v4 generation works under the hood, you can use the Web Crypto API directly:

function generateUUID() {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);

  // Set version (4) in bits 12-15 of time_hi_and_version
  bytes[6] = (bytes[6] & 0x0f) | 0x40;
  // Set variant (10) in bits 6-7 of clock_seq_hi_and_reserved
  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),
  ].join("-");
}

This generates 16 cryptographically random bytes, sets the version and variant bits according to the UUID spec, and formats the result as a hyphenated hex string.

Method 3: The uuid Package

For projects that need backward compatibility with older environments or additional UUID versions, the uuid npm package is the most popular choice:

npm install uuid
import { v4 as uuidv4 } from "uuid";

const id = uuidv4();
console.log(id); // "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

The uuid package also supports v1 (timestamp-based), v3 (MD5 namespace), v5 (SHA-1 namespace), and v7 (timestamp-ordered) UUIDs.

When to Use UUID v4

Database Primary Keys

UUID v4 is commonly used as a primary key in databases, especially in distributed systems where auto-incrementing integers would create conflicts. However, be aware that random UUIDs cause B-tree index fragmentation. If insert performance matters, consider UUID v7 (timestamp-ordered) or ULID instead.

Session Tokens

UUIDs generated with crypto.randomUUID() are cryptographically random and suitable for session identifiers, CSRF tokens, and other security-sensitive contexts.

Idempotency Keys

When making API requests that should not be processed twice (like payment submissions), include a UUID as an idempotency key in the request header.

Correlation IDs

In microservice architectures, attach a UUID to each incoming request and propagate it through all downstream service calls for distributed tracing.

UUID v4 vs Other Identifiers

UUID v7

UUID v7 embeds a Unix timestamp in the first 48 bits, making the IDs time-sortable while still being unique. This solves the B-tree fragmentation problem of v4 and is increasingly preferred for database primary keys.

ULID

Universally Unique Lexicographically Sortable Identifiers combine a timestamp with randomness, are encoded in Crockford Base32 (26 characters), and sort naturally. They are a popular alternative when you want human-readable, sortable IDs.

nanoid

If you need shorter IDs and do not need UUID format compatibility, nanoid generates URL-safe, unique IDs with customizable length:

import { nanoid } from "nanoid";
const id = nanoid(); // "V1StGXR8_Z5jdHi6B-myT"

Bulk UUID Generation

Need to generate many UUIDs at once for testing, seeding a database, or populating mock data? The devcraft UUID Generator lets you generate up to hundreds of UUID v4 identifiers in bulk with a single click, ready to copy and paste.

Common Pitfalls

  • Do not use Math.random() — It is not cryptographically secure and produces predictable values. Always use crypto.randomUUID() or crypto.getRandomValues().
  • Do not assume ordering — UUID v4 values are random and have no inherent order. If you need sortable IDs, use UUID v7 or ULID.
  • Watch for collisions in theory — While the probability of a v4 collision is astronomically low (you would need to generate about 2.71 quintillion UUIDs for a 50% chance), never assume uniqueness in security-critical contexts without additional safeguards.

Generate UUIDs instantly with the devcraft UUID Generator — no signup, no installation, completely free.