Skip to main content

Generate UUID in JavaScript: crypto.randomUUID() Guide

Generate UUIDs in JavaScript using crypto.randomUUID(), the uuid npm package, and manual implementations. Browser and Node.js examples.

How to Generate UUIDs in JavaScript

Since 2021, modern browsers and Node.js 19+ include crypto.randomUUID() — a native, cryptographically secure UUID v4 generator that requires no external dependencies. For older environments, the uuid npm package remains the standard choice with over 100 million weekly downloads.

Native: crypto.randomUUID()

// Browser (Chrome 92+, Firefox 95+, Safari 15.4+)
const id = crypto.randomUUID();
console.log(id); // \"3b241101-e2bb-4d52-8376-9e5c8e1f3a41\"

// Node.js 19+
const { randomUUID } = require(\"crypto\");
console.log(randomUUID()); // Same format

// Generate multiple UUIDs
const ids = Array.from({ length: 10 }, () => crypto.randomUUID());
console.log(ids);

npm uuid Package

// Install: npm install uuid
const { v4: uuidv4 } = require(\"uuid\");

const id = uuidv4();
console.log(id); // \"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d\"

// Validate a UUID
const { validate } = require(\"uuid\");
console.log(validate(\"not-a-uuid\")); // false
console.log(validate(id));            // true

// Detect UUID version
const { version } = require(\"uuid\");
console.log(version(id)); // 4

Manual Implementation (No Dependencies)

If you cannot use crypto.randomUUID() and do not want a dependency, here is a minimal implementation using crypto.getRandomValues():

function generateUUID() {
    const bytes = new Uint8Array(16);
    crypto.getRandomValues(bytes);
    // Set version 4 (0100) in byte 6
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    // Set variant 1 (10xx) in byte 8
    bytes[8] = (bytes[8] & 0x3f) | 0x80;
    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, 16).join(\"\")
    ].join(\"-\");
}

When to Use UUIDs in JavaScript

  • Database primary keys — generate IDs client-side before inserting, enabling offline-first apps and optimistic UI updates
  • Temporary IDs — assign unique IDs to DOM elements, form fields, or component instances
  • Idempotency keys — prevent duplicate API submissions by attaching a UUID to each request
  • Session identifiers — track anonymous users or browser sessions without cookies
  • File naming — generate unique filenames for uploads to prevent collisions in cloud storage

Browser Support

crypto.randomUUID() is supported in Chrome 92+, Edge 92+, Firefox 95+, Safari 15.4+, and Node.js 19+. For older browsers, use the uuid package or the manual implementation above. Always check typeof crypto.randomUUID === \"function\" before using the native method.

Try UUID v4 Generator Free

Generate unique UUID v4 identifiers.

Use UUID v4 Generator →