Blog

How to Generate a UUID in JavaScript

Generate UUIDs in JavaScript the modern way with crypto.randomUUID, plus Node.js options and why you should avoid Math.random for IDs.

Modern JavaScript can generate cryptographically strong UUIDs with one line — no library needed.

The modern way: crypto.randomUUID

js
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:

js
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.randomUUID exists.

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 file to check?
Paste it in. Errors come back in plain English.
Open UUID Generator →