How to Generate UUIDs in JavaScript
Generating UUIDs in JavaScript has never been easier. Modern browsers and Node.js now include built-in UUID generation. This tutorial covers native methods, popular libraries, and advanced techniques for creating unique identifiers in your applications.
Method 1: Native crypto.randomUUID() (Recommended)
The modern, built-in way to generate UUIDs:
// Browser and Node.js 14.17+
const uuid = crypto.randomUUID();
console.log(uuid);
// "3f0e9a7c-8b2d-4f1a-9c3e-5d6f7a8b9c0d"Browser Support
| Browser | Version | |---------|---------| | Chrome | 92+ | | Firefox | 95+ | | Safari | 15.4+ | | Edge | 92+ | | Node.js | 14.17+ |
Advantages
- ✅ No dependencies
- ✅ Cryptographically secure
- ✅ Fast performance
- ✅ Standard UUID v4 format
Method 2: Using the uuid Library
For older environments or additional UUID versions:
npm install uuidimport { v4 as uuidv4, v7 as uuidv7 } from 'uuid';// Generate UUID v4 (random)
const id = uuidv4();
console.log(id);
// "550e8400-e29b-41d4-a716-446655440000"
// Generate UUID v7 (timestamp-based, sortable)
const sortableId = uuidv7();
console.log(sortableId);
// "017f22e2-79b0-7cc3-98c4-dc0c0c0c0c0c"
Why Use the uuid Library?
- Supports multiple UUID versions (v1, v3, v4, v5, v7)
- Works in older browsers
- More control over generation
- Well-tested and maintained
Method 3: Custom Implementation (Educational)
Understanding how UUID v4 works internally:
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());
// "550e8400-e29b-41d4-a716-446655440000"
⚠️ Note: This uses Math.random() which is NOT cryptographically secure. Use crypto.randomUUID() for production.
UUID Versions Explained
| Version | Type | Use Case | |---------|------|----------| | v1 | Time + MAC address | Legacy, traceable | | v3 | MD5 hash + namespace | Reproducible from name | | v4 | Random | General purpose (most common) | | v5 | SHA-1 hash + namespace | Reproducible, more secure | | v7 | Timestamp + random | Sortable, database-friendly |
Common Use Cases
Database Primary Keys
// Generate unique ID for new record
const userId = crypto.randomUUID();await db.query(
'INSERT INTO users (id, email) VALUES (?, ?)',
[userId, '[email protected]']
);
Session Identifiers
// Express.js session middleware
app.use((req, res, next) => {
req.sessionId = crypto.randomUUID();
next();
});Request Tracking
// Add trace ID to every request
async function fetchWithTrace(url, options = {}) {
const traceId = crypto.randomUUID(); const response = await fetch(url, {
...options,
headers: {
...options.headers,
'X-Trace-ID': traceId
}
});
console.log(Request ${traceId} completed);
return response;
}
File Naming
import { join } from 'path';
import { extname } from 'path';function generateUniqueFilename(originalName) {
const ext = extname(originalName);
const uuid = crypto.randomUUID();
return ${uuid}${ext};
}
// "photo.jpg" → "550e8400-e29b-41d4-a716-446655440000.jpg"
Generating Multiple UUIDs
Batch Generation
// Generate 10 UUIDs
const uuids = Array(10).fill(null).map(() => crypto.randomUUID());console.log(uuids);
// ["uuid1", "uuid2", ...]
UUID Generator Function
class IdGenerator {
static generate(count = 1) {
if (count === 1) {
return crypto.randomUUID();
}
return Array(count).fill(null).map(() => crypto.randomUUID());
} static generateWithPrefix(prefix, count = 1) {
if (count === 1) {
return ${prefix}-${crypto.randomUUID()};
}
return Array(count).fill(null).map(() => ${prefix}-${crypto.randomUUID()});
}
}
// Usage
const singleId = IdGenerator.generate();
const batchIds = IdGenerator.generate(100);
const prefixedIds = IdGenerator.generateWithPrefix('user', 5);
UUID v7: The New Standard
UUID v7 combines timestamps with random data for sortable IDs:
import { v7 as uuidv7 } from 'uuid';const id1 = uuidv7(); // "017f22e2-79b0-7cc3-98c4-dc0c0c0c0c0c"
const id2 = uuidv7(); // "017f22e2-79b0-7cc3-98c4-dc0c0c0c0c0d"
// id2 > id1 (sortable!)
console.log(id2 > id1); // true
Why UUID v7?
- Sortable by time - no separate index needed
- Better database locality - sequential writes
- Still unique - combines timestamp with randomness
Polyfill for Older Environments
// Add crypto.randomUUID() if not available
if (!crypto.randomUUID) {
crypto.randomUUID = function() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes); // Set version (4) and variant bits
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = [...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)};
};
}
// Now you can use crypto.randomUUID() everywhere
const uuid = crypto.randomUUID();
Complete UUID Utility Class
class UUID {
static generate() {
return crypto.randomUUID();
} static generateBatch(count) {
return Array(count).fill(null).map(() => crypto.randomUUID());
}
static validate(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);
}
static getVersion(uuid) {
if (!this.validate(uuid)) return null;
return parseInt(uuid[14], 10);
}
static strip(uuid) {
return uuid.replace(/-/g, '');
}
static format(uuid) {
const stripped = this.strip(uuid);
return ${stripped.slice(0, 8)}-${stripped.slice(8, 12)}-${stripped.slice(12, 16)}-${stripped.slice(16, 20)}-${stripped.slice(20)};
}
}
// Usage
console.log(UUID.generate());
console.log(UUID.validate('invalid-uuid'));
console.log(UUID.getVersion(UUID.generate())); // 4
Try It Online
Need quick UUIDs without coding? Use our UUID Generator to generate single or batch UUIDs with various format options.
Conclusion
For modern applications, use crypto.randomUUID()—it's built-in, secure, and fast. For UUID v7 or older browser support, the uuid library is excellent.
For more JavaScript utilities, see How to Format JSON in JavaScript.
---
Related Tools: