Generate UUID in Node.js
Node.js has built-in UUID v4 generation via crypto.randomUUID() since v14.17.0 — zero dependencies, OS CSPRNG-backed. Use the uuid package for v7 and v5 support.
Quick Reference
| Function | Version | Sortable | Use Case |
|---|---|---|---|
| crypto.randomUUID() | v4 | No | General purpose — zero deps, built-in since Node 14.17 |
| uuidv7() from uuid | v7 | Yes | Database PKs, event logs — time-ordered |
| uuidv5() from uuid | v5 | No | Deterministic — same namespace + name = same UUID |
Primary Implementation
// ESM (Node.js 14.17+ — recommended)
import { randomUUID } from 'crypto';
// CommonJS
// const { randomUUID } = require('crypto');
// Generate a UUID v4 — zero dependencies
const id = randomUUID();
console.log(id);
// → "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Generate multiple
const ids = Array.from({ length: 5 }, () => randomUUID());
// Parse / validate (no built-in — use a regex or the uuid package)
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isValidUUID(str) {
return UUID_REGEX.test(str);
}
console.log(isValidUUID(id)); // → true
All UUID Versions
UUID v4 — Random (built-in, no deps)
import { randomUUID } from 'crypto';
// 122 bits of randomness — backed by libuv → OS CSPRNG
const id = randomUUID();
// → "550e8400-e29b-41d4-a716-446655440000"
UUID v7 — Time-ordered (requires uuid package)
// npm install uuid
import { v7 as uuidv7 } from 'uuid';
// Millisecond-precision timestamp prefix — sorts chronologically
const id = uuidv7();
// → "018e8f6a-1b2c-7d3e-9f4a-5b6c7d8e9f0a"
UUID v5 — Deterministic / Namespace-based
import { v5 as uuidv5 } from 'uuid';
// SHA-1 hash of namespace + name — same inputs always produce the same UUID
const id = uuidv5('example.com', uuidv5.DNS);
// → always "cfbff0d1-9375-5685-968c-48ce8b15ae17"
Real-World Use Cases
1. Express middleware — request tracing ID
import express from 'express';
import { randomUUID } from 'crypto';
const app = express();
// Inject a unique request ID into every request
app.use((req, res, next) => {
req.id = randomUUID();
res.setHeader('X-Request-ID', req.id);
next();
});
app.get('/orders', (req, res) => {
console.log(`[${req.id}] GET /orders`);
res.json({ requestId: req.id });
});
2. Prisma — UUID primary key
// schema.prisma
// model User {
// id String @id @default(uuid())
// name String
// }
import { PrismaClient } from '@prisma/client';
import { randomUUID } from 'crypto';
const prisma = new PrismaClient();
// Prisma generates the UUID automatically via @default(uuid())
// Or supply your own for idempotent inserts:
async function createUser(name) {
return prisma.user.create({
data: { id: randomUUID(), name },
});
}
3. Idempotency key for payment APIs
import { randomUUID } from 'crypto';
// Generate once, store, reuse on retry — prevents duplicate charges
async function chargeCustomer(customerId, amount) {
const idempotencyKey = randomUUID();
const response = await fetch('https://api.stripe.com/v1/charges', {
method: 'POST',
headers: {
'Idempotency-Key': idempotencyKey,
'Authorization': `Bearer ${process.env.STRIPE_KEY}`,
},
body: new URLSearchParams({ customer: customerId, amount }),
});
return response.json();
}
Common Mistakes
Using Math.random() for IDs
Math.random() is not cryptographically secure and only provides ~53 bits of entropy. Always use crypto.randomUUID() which is backed by the OS CSPRNG via libuv.
Installing the uuid package just for v4
If you only need UUID v4, crypto.randomUUID() is built-in since Node 14.17. Only add the uuid package when you need v7, v5, or v3.
Mixing ESM and CJS imports
Use import { randomUUID } from 'crypto' in ESM projects and const { randomUUID } = require('crypto') in CJS. Mixing them causes runtime errors. Check your package.json "type" field.
How It Works
crypto.randomUUID() is implemented in V8/libuv and calls the OS CSPRNG directly — /dev/urandom on Linux/macOS and BCryptGenRandom on Windows. It fills 122 bits with random data and sets the version (4) and variant bits per RFC 4122.
The function always returns a lowercase hyphenated string. It is synchronous and does not block the event loop — the OS entropy call is non-blocking.
Output Formats
randomUUID()
f47ac10b-58cc-4372-a567-0e02b2c3d479
No hyphens
randomUUID().replace(/-/g, '')
Uppercase
randomUUID().toUpperCase()
Best Practices
Use crypto.randomUUID() for v4 — it's built-in, fast, and zero dependencies.
Use UUID v7 for database primary keys — sequential inserts avoid index fragmentation.
Store UUIDs as lowercase strings for consistency across systems.
Performance
Native crypto.randomUUID() runs at roughly 5–10 million UUIDs/second in Node.js. It is implemented in C++ and calls the OS CSPRNG via libuv.
The call is synchronous but non-blocking — it does not yield to the event loop, making it safe to call in hot paths.
Installation
# No installation needed for v4 (Node 14.17+)
npm install uuid # for v7, v5, v3
Requires Node.js 14.17.0 or later for the built-in. The uuid npm package works on all Node versions.
Security
Entropy source: libuv → OS CSPRNG (/dev/urandom on Linux/macOS, BCryptGenRandom on Windows). Cryptographically secure.
Suitable for session tokens, CSRF tokens, and API keys. Never use Math.random() for security-sensitive IDs.