How to Generate a UUID in JavaScript
Generating unique identifiers is one of the most common tasks in web development โ for database records, API resources, session tokens, and temporary file names. JavaScript now has a built-in UUID generator that works in both browsers and Node.js, no library required.
- Generate UUID v4 and v7 in JavaScript using crypto.
- The Modern Way: crypto.randomUUID().
- Covers fallback for older environments.
- The uuid npm Package.
- When to Use Each Version.
The Modern Way: crypto.randomUUID()
Since 2021, all modern browsers and Node.js 19+ support crypto.randomUUID():
const id = crypto.randomUUID();
// '550e8400-e29b-41d4-a716-446655440000'
This generates a cryptographically random UUID v4 โ the format used by most applications. It's fast, secure, and requires no dependencies. This is the recommended approach for all new projects.
Fallback for Older Environments
If you need to support older browsers or Node.js versions before 19, use the Web Crypto API directly:
function uuidv4() {
return '10000000-1000-4000-8000-100000000000'
.replace(/[018]/g, c => (
c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4
).toString(16));
}
This uses crypto.getRandomValues() for cryptographic randomness โ never use Math.random() for UUIDs, as it doesn't provide sufficient entropy and can produce collisions.
The uuid npm Package
For projects that need UUID v1 (timestamp-based), v3 (namespace + MD5), v5 (namespace + SHA-1), or v7 (timestamp + random), the uuid npm package is the standard:
background-size animation or @property registered custom properties instead.import { v4, v7 } from 'uuid';
const id = v4(); // random UUID
const sortable = v7(); // time-sorted UUID
UUID v7 is increasingly preferred for database primary keys because it's time-sorted, which improves database index performance compared to random v4 UUIDs.
When to Use Each Version
Use UUID v4 for most cases โ session IDs, temporary identifiers, and any context where sort order doesn't matter. Use UUID v7 for database primary keys where time-based sorting improves query performance. Avoid UUID v1 (it exposes the machine's MAC address). For bulk generation or testing, the UUID Generator tool creates multiple UUIDs instantly in any version.