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:
UUID v4 Structure
A UUID v4 has the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx:
| Part | Length | Meaning |
|---|---|---|
| time_low | 8 hex (32 bits) | Random bits |
| time_mid | 4 hex (16 bits) | Random bits |
| time_hi_and_version | 4 hex (16 bits) | Top 4 bits = version (0100 = v4) |
| clock_seq | 4 hex (16 bits) | Top 2 bits = variant (10xx) |
| node | 12 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:
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:
React & Next.js SSR Considerations
Generating UUIDs for React keys or element IDs has server/client pitfalls:
TypeScript Typed UUID Functions
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.