How to Generate UUID v4 in JavaScript (3 Methods)
UUID v4 (Universally Unique Identifier version 4) is a 128-bit identifier generated from random or pseudo-random numbers. It follows the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where 4 indicates the version and y is one of 8, 9, a, or b to indicate the variant.
JavaScript now offers multiple ways to generate UUID v4 values. This guide covers three methods, ranked from best to acceptable, with complete code examples and browser/Node.js compatibility notes.
Method 1: crypto.randomUUID() (Recommended)
The simplest and most correct way to generate a UUID v4 in JavaScript is the built-in crypto.randomUUID() method. It was added to the Web Crypto API specifically for this purpose.
const uuid = crypto.randomUUID();
console.log(uuid);
// Output: "3b241101-e2bb-4d7a-8702-9e8c38b8f104"
This method is:
- Cryptographically secure — uses the OS entropy pool, not Math.random()
- RFC 4122 compliant — always produces valid UUID v4 with correct version and variant bits
- Zero dependencies — built into the platform
- Fast — native implementation, no JavaScript overhead
Browser Support
crypto.randomUUID() is supported in Chrome 92+, Firefox 95+, Safari 15.4+, and Edge 92+. It requires a secure context (HTTPS or localhost). In Node.js, it is available from version 19+ globally, or via require('crypto') from Node.js 14.17+.
// Node.js (14.17+)
const { randomUUID } = require('node:crypto');
console.log(randomUUID());
// Node.js (19+ global)
console.log(crypto.randomUUID());
If you need to support older browsers that lack crypto.randomUUID(), use Method 2 or Method 3 below.
Method 2: Manual Construction with crypto.getRandomValues()
If you need to support environments without crypto.randomUUID(), you can build a compliant UUID v4 from raw random bytes. This method works in every browser that supports the Web Crypto API (IE 11+, all modern browsers).
function generateUUIDv4() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
// Set version bits (4) in byte 6
bytes[6] = (bytes[6] & 0x0f) | 0x40;
// Set variant bits (10xx) in byte 8
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('');
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32)
].join('-');
}
console.log(generateUUIDv4());
// Output: "f47ac10b-58cc-4372-a567-0e02b2c3d479"
How It Works
- Generate 16 random bytes (128 bits) using
crypto.getRandomValues() - Set the version: byte 6 must have its high nibble set to
0x4(binary0100), indicating UUID version 4 - Set the variant: byte 8 must have its two most significant bits set to
10(binary), indicating the RFC 4122 variant - Format as string: convert to hex and insert hyphens at positions 8-4-4-4-12
This is exactly what crypto.randomUUID() does internally. The only downside of the manual approach is that you own the implementation and must ensure correctness.
Method 3: The uuid npm Package
The uuid package is the most downloaded UUID library on npm, with over 100 million weekly downloads. It supports UUID versions 1 through 7.
npm install uuid
import { v4 as uuidv4 } from 'uuid';
console.log(uuidv4());
// Output: "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"
The uuid package uses crypto.getRandomValues() under the hood when available, falling back to Node.js crypto.randomBytes(). It also supports UUID v1 (timestamp-based), v3 and v5 (namespace-based), and the newer v6 and v7 (sortable timestamp-based).
import { v1, v4, v5, v7 } from 'uuid';
// v1: timestamp + MAC address
console.log(v1()); // "6c84fb90-12c4-11e1-840d-7b25c5ee775a"
// v4: random
console.log(v4()); // "110ec58a-a0f2-4ac4-8393-c866d813b8d1"
// v5: SHA-1 namespace
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
console.log(v5('hello', MY_NAMESPACE)); // deterministic
// v7: Unix timestamp + random (sortable)
console.log(v7()); // "01906b39-6b74-7..."
Use the uuid package when you need UUID versions other than v4, or when you need to validate and parse existing UUIDs. For simple v4 generation, crypto.randomUUID() is preferred.
Comparison Table
| Method | Secure | Dependencies | Browser | Node.js | Best For |
|---|---|---|---|---|---|
crypto.randomUUID() | Yes | None | Chrome 92+ | 14.17+ | Modern apps |
| Manual + getRandomValues | Yes | None | IE 11+ | All | Legacy support |
| uuid npm package | Yes | 1 package | All | All | Multiple UUID versions |
Common Mistakes to Avoid
1. Using Math.random()
You will find hundreds of Stack Overflow answers suggesting UUID generation with Math.random(). Every single one is wrong for production use. Math.random() is not cryptographically secure, and its output can be predicted after observing enough values.
// DO NOT use this in production
function badUUID() {
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);
});
}
This pattern generates syntactically valid UUIDs but with insufficient entropy. If your UUIDs serve any security purpose (session tokens, API keys, database identifiers that must not be guessable), use one of the three methods above.
2. Forgetting Version and Variant Bits
If you build UUIDs manually, you must set the version nibble to 4 and the variant bits to 10. Omitting these steps produces random 128-bit strings that look like UUIDs but violate RFC 4122, which can cause validation failures in systems that check UUID conformance.
3. Assuming UUIDs Are Sequential
UUID v4 values are random, not sequential. If you need time-ordered identifiers (for database indexing or pagination), use UUID v7, which embeds a Unix timestamp in the most significant bits while keeping the remaining bits random.
UUID v4 vs UUID v7: Which Should You Use?
UUID v7 (defined in RFC 9562, finalized in 2024) is the modern alternative to v4 for database primary keys. It preserves the 128-bit UUID format but encodes a millisecond-precision timestamp in the first 48 bits, making the IDs naturally sortable by creation time.
- Use UUID v4 when you need identifiers with no temporal information (tokens, API keys, anonymous IDs)
- Use UUID v7 when you need sortable, time-ordered identifiers (database PKs, event IDs, log correlation)
Both versions are cryptographically random in their random segments and are equally resistant to guessing attacks.
Generate UUIDs Instantly
Need a UUID right now? Use our free UUID generator which uses crypto.randomUUID() directly in your browser. No server, no tracking, no storage.
Recommended Resources
For mastering JavaScript's crypto APIs including randomUUID(), JavaScript: The Definitive Guide is the authoritative reference. To understand the cryptographic randomness behind UUID v4, Real-World Cryptography explains CSPRNGs and entropy in detail.