How to Generate a UUID in JavaScript

Use the platform-native API in modern runtimes, and the browser UUID generator when you only need a few test values.

UUID generation is one of those tasks where the right answer depends entirely on which runtime you are in. The native crypto APIs cover almost every modern environment; everything else is a workaround.

1. Use crypto.randomUUID (Node 14.17+, all modern browsers)

const id = crypto.randomUUID();
// '5b1d6f3c-2a85-4f9d-8a30-1c4b3a8b9d12'

This produces a v4 UUID using cryptographically strong randomness. Available globally on Node 19+ and as crypto.randomUUID() on Node 14.17+ via require('crypto').randomUUID(). In browsers it lives on window.crypto.

2. Fall back to crypto.getRandomValues

function uuidv4() { const bytes = crypto.getRandomValues(new Uint8Array(16)); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = [...bytes].map(b => b.toString(16).padStart(2, '0')).join(''); return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
}

The two bit operations enforce the v4 version (set byte 6) and variant (set byte 8) requirements from RFC 4122.

3. Avoid Math.random

Math.random is not cryptographically random and produces noticeable collisions at scale. The only reason to use it is if you genuinely cannot reach a Web Crypto implementation, which is rare.

When to switch to the browser tool

If you just need a handful of UUIDs for fixtures, tests, or a quick database insert, generating them in code is overkill. Open UUID Generator and copy as many as you need. The same page validates whether an existing string is a well-formed UUID.

For the broader topic, browse Developer Utility Tools. If you also need to hash values to verify a fixture, jump to Hash Generator.