How to Generate a UUID in JavaScript
Modern JavaScript can generate cryptographically strong UUIDs with one line — no library needed.
The modern way: crypto.randomUUID
const id = crypto.randomUUID();
// "550e8400-e29b-41d4-a716-446655440000"
This is built into all modern browsers and Node.js 16+. It returns a version 4 UUID using a cryptographically secure random source. This is what you should use.
In Node.js
crypto.randomUUID works in Node too:
import { randomUUID } from 'node:crypto';
const id = randomUUID();
Don't use Math.random
You'll see snippets that build UUIDs from Math.random(). Avoid them:
Math.random()is not cryptographically secure and can produce predictable or colliding values.- It's unnecessary now that
crypto.randomUUIDexists.
Need v7 (sortable)?
crypto.randomUUID produces v4. For time-ordered v7 UUIDs (great for database keys), use a small library like uuidv7, since they aren't built in yet.
Generate without code
Just need a few UUIDs right now? The UUID generator produces them instantly in your browser.
Got a config file to check?
Open the config toolkit →