UUID v4 Generation in JavaScript โ What They Are and When to Use Them
UUID v4 generates 128-bit random identifiers suitable for database primary keys, session IDs, and API request tracing.
UUIDs are everywhere in backend development. Every database record, every session, every uploaded file probably has one. Generating them correctly in JavaScript is simple but there are some common mistakes to avoid.
Generating UUID v4 in modern JavaScript
Since Node.js 14.17 and all modern browsers, you don't need any library. The crypto.randomUUID() method generates a cryptographically secure UUID v4:
// Node.js (14.17+) or modern browser const id = crypto.randomUUID(); // "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d" // Also available as Web Crypto API const id = self.crypto.randomUUID();
That's the whole thing. No library, no dependencies. This is what you should use for any new code.
The uuid npm package (for older environments)
If you need to support older Node.js versions or need UUID v1/v7, the uuid package is the standard:
import { v4 as uuidv4, v7 as uuidv7 } from "uuid";
const id = uuidv4(); // random v4
const orderedId = uuidv7(); // time-ordered v7 (better for database PKs)UUID v4 vs UUID v7: which to use
UUID v4 is 122 bits of randomness. It's the right choice for:
- API resource identifiers exposed publicly
- Session tokens
- File names for uploaded content
UUID v7 starts with a millisecond timestamp, making it sortable. Use it for:
- Database primary keys (sortable IDs index better in B-trees)
- Event IDs in distributed systems where ordering matters
Storing UUIDs in databases
PostgreSQL has a native uuidtype that stores 16 bytes efficiently. MySQL 8 also supports it. If your database doesn't have a UUID type, store as CHAR(36) (with hyphens) or BINARY(16)(without hyphens, more compact). Never store UUIDs as VARCHAR if you can help it.
Generate UUIDs for testing with our UUID Generator.