Generate UUIDs in JavaScript

How to generate UUIDs in JavaScript and Node.js: crypto.randomUUID(), the uuid npm package, and custom implementations for v4 and v7 with code examples.

Usage

Detailed Explanation

JavaScript offers multiple approaches to UUID generation, from native browser APIs to popular npm packages. Here is a comprehensive guide to each method and when to use it.

Method 1: crypto.randomUUID() (recommended) Available in all modern browsers (Chrome 92+, Firefox 95+, Safari 15.4+) and Node.js 19+:

const id = crypto.randomUUID();
// "36b8f84d-df4e-4d49-b662-bcde71a8764f"

This is the simplest and most performant option. It uses the operating system's cryptographic random number generator and returns a properly formatted UUID v4 string. No dependencies required.

Method 2: The uuid npm package The most popular UUID library with 50M+ weekly downloads. Supports all UUID versions:

import { v4 as uuidv4, v7 as uuidv7, v5 as uuidv5 } from 'uuid';

const random = uuidv4();        // Random UUID v4
const timeBased = uuidv7();     // Time-ordered UUID v7
const named = uuidv5('example.com', uuidv5.DNS); // Name-based v5

// Validation
import { validate, version } from 'uuid';
validate('not-a-uuid');              // false
validate('36b8f84d-df4e-4d49-b662-bcde71a8764f'); // true
version('36b8f84d-df4e-4d49-b662-bcde71a8764f');  // 4

Method 3: Custom implementation (when you need control)

// UUID v4 from scratch
function uuidv4() {
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  bytes[6] = (bytes[6] & 0x0f) | 0x40;  // Version 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80;  // Variant 10
  const hex = [...bytes].map(b => b.toString(16).padStart(2, '0'));
  return `${hex.slice(0,4).join('')}-${hex.slice(4,6).join('')}-${hex.slice(6,8).join('')}-${hex.slice(8,10).join('')}-${hex.slice(10).join('')}`;
}

Performance benchmarks (Node.js 20, Apple M2):

crypto.randomUUID():     8.2M ops/sec
uuid.v4():              5.1M ops/sec
uuid.v7():              3.8M ops/sec
Custom implementation:   2.4M ops/sec

crypto.randomUUID() is fastest because it is implemented natively in C++ within the runtime.

Common pitfalls:

  1. Do not use Math.random() for UUID generation. It is not cryptographically secure and can produce duplicates.
  2. SSR hydration mismatch: Generating UUIDs during server-side rendering produces different values on server and client. Use useId() in React for DOM element IDs, or generate UUIDs only in event handlers / useEffect.
  3. Bundle size: If you only need v4, crypto.randomUUID() adds zero bytes to your bundle. The uuid package adds ~4.5KB (minified).

TypeScript typing:

// The return type of crypto.randomUUID() is `string`
// For stricter typing, use a branded type:
type UUID = string & { readonly __brand: 'UUID' };
function generateId(): UUID {
  return crypto.randomUUID() as UUID;
}

Use Case

JavaScript UUID generation is needed in virtually every web application for creating unique keys in React lists, generating idempotency tokens for API requests, and assigning session identifiers on the client side.

Try It — UUID Generator

Open full tool