Generate UUID in JavaScript — crypto.randomUUID() & Libraries

JavaScript now has a native UUID generator built into the Web Crypto API: crypto.randomUUID(). It requires no libraries, is cryptographically secure, and works in all modern browsers and Node.js 16+. This guide covers usage, browser support, fallbacks, and TypeScript types.

crypto.randomUUID() — Modern Browsers & Node 16+

The simplest approach — one line, no imports, cryptographically secure:

// Browser and Node.js 16.7+ const id = crypto.randomUUID(); // → '110e8400-e29b-41d4-a716-446655440000' // Requirement: HTTPS or localhost (secure context) // In Node.js — available globally, no import needed: const { randomUUID } = require('crypto'); const id = randomUUID(); // Or with ES modules: import { randomUUID } from 'node:crypto'; const id = randomUUID();

UUID v4 Structure

A UUID v4 has the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx:

550e8400-e29b-41d4-a716-446655440000 ^^^^^^^^ ^^^^ ^^^^ ^^^^ ^^^^^^^^^^^^ 8 4 4 4 12 (hex chars per group) 32 bits ↑ ↑ | └── y = 8, 9, a, or b (variant 1) └──── 4 = version 4
PartLengthMeaning
time_low8 hex (32 bits)Random bits
time_mid4 hex (16 bits)Random bits
time_hi_and_version4 hex (16 bits)Top 4 bits = version (0100 = v4)
clock_seq4 hex (16 bits)Top 2 bits = variant (10xx)
node12 hex (48 bits)Random bits

Browser Support & Fallback Polyfill

crypto.randomUUID() requires a secure context (HTTPS or localhost). For HTTP development servers or older browser support, use this polyfill:

function generateUUID() { // Use native API if available (secure context) if (typeof crypto !== 'undefined' && crypto.randomUUID) { return crypto.randomUUID(); } // Fallback using getRandomValues if (typeof crypto !== 'undefined' && crypto.getRandomValues) { return '10000000-1000-4000-8000-100000000000'.replace( /[018]/g, (c) => ( Number(c) ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4))) ).toString(16) ); } // Last resort: Math.random (NOT cryptographically secure) return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); }

UUID in Node.js — uuid npm Package

For Node.js projects that need multiple UUID versions or older Node.js support, the uuid package is the standard:

npm install uuid import { v4 as uuidv4, v7 as uuidv7, validate, version } from 'uuid'; const id = uuidv4(); // → '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' const id7 = uuidv7(); // → '018fdb73-e8a7-7b8a-b3f5-6c7b8a9d0e1f' // UUID v7 is time-ordered — good for database primary keys // Validate a UUID validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'); // true validate('not-a-uuid'); // false // Get version of a UUID version('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'); // 4

React & Next.js SSR Considerations

Generating UUIDs for React keys or element IDs has server/client pitfalls:

// BAD: generates different ID on server vs client → hydration mismatch function BadComponent() { const id = crypto.randomUUID(); // Different every render! return <input id={id} />; } // GOOD: use useId hook (React 18+) for stable SSR-safe IDs import { useId } from 'react'; function GoodComponent() { const id = useId(); // Stable across server and client renders return <input id={id} />; } // GOOD: generate UUID once in state (client-only) import { useState } from 'react'; function ClientOnlyId() { const [id] = useState(() => crypto.randomUUID()); return <div data-id={id}>...</div>; } // GOOD: generate UUIDs server-side, pass as props // In a Server Component or getServerSideProps: const items = data.map(item => ({ ...item, id: item.id ?? crypto.randomUUID(), // assign once }));

TypeScript Typed UUID Functions

// Branded type for UUIDs (prevents mixing regular strings with IDs) type UUID = string & { readonly __brand: 'UUID' }; function generateId(): UUID { return crypto.randomUUID() as UUID; } // Type-safe entity with UUID interface User { id: UUID; name: string; email: string; } function createUser(name: string, email: string): User { return { id: generateId(), name, email, }; } // Type guard function isUUID(value: string): value is UUID { return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value); }

Related Tools

Related Guides

FAQ

What is the fastest way to generate a UUID in JavaScript?

In modern browsers and Node.js 16+, use crypto.randomUUID() — it's a single function call, no libraries needed, and uses a cryptographically secure random number generator. It returns a UUID v4 string.

Is crypto.randomUUID() supported in all browsers?

crypto.randomUUID() is supported in Chrome 92+, Firefox 95+, Safari 15.4+, Edge 92+, and Node.js 16.7+. It's only available in secure contexts (HTTPS or localhost). For older browser support or HTTP contexts, use a polyfill or the uuid npm package.

What is a UUID v4?

UUID v4 is a randomly generated 128-bit identifier in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where 4 indicates version 4 and y is one of 8, 9, a, or b (variant bits). The rest is random, giving 122 bits of randomness — making collisions astronomically unlikely.

Can I use UUID in React Server Components?

Yes, crypto.randomUUID() is available in Node.js server environments. However, generating UUIDs in Server Components means the ID changes on every render/request — store UUIDs in state or database, don't generate them inline in render.

Should I use uuid v4 or v7?

UUID v4 is fully random and the most common. UUID v7 is time-ordered (sortable by creation time), which is useful for database primary keys because it avoids random writes and improves index locality. For database IDs, v7 is increasingly preferred.