How to Generate UUID in JavaScript

Modern JavaScript provides built-in support for generating RFC 4122 compliant UUIDs using the crypto.randomUUID() API. This guide covers all methods for generating UUIDs in both Node.js and browser environments.

1. Using crypto.randomUUID() (Recommended)

The simplest and most secure way to generate a UUID v4 in modern browsers and Node.js 19+.

// Works in browsers and Node.js 19+
const uuid = crypto.randomUUID();
console.log(uuid);
// Output: "550e8400-e29b-41d4-a716-446655440000"

2. Using the uuid npm Package

For older Node.js versions or when you need more UUID versions.

npm install uuid
import { v4 as uuidv4, v1 as uuidv1 } from 'uuid';

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

// Generate UUID v1 (timestamp-based)
const id1 = uuidv1();
console.log(id1); // "2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d"

3. Browser Fallback (Legacy)

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

console.log(generateUUID());

4. UUID Validation

function isValidUUID(uuid) {
  const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return regex.test(uuid);
}

console.log(isValidUUID("550e8400-e29b-41d4-a716-446655440000")); // true
console.log(isValidUUID("not-a-uuid")); // false

5. Generate Multiple UUIDs

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

UUID Methods Comparison

Method Environment Version
crypto.randomUUID() Browser, Node 19+ v4
uuid.v4() All v4
uuid.v1() All v1

Ready to use what you learned?

Try UUID Generator now