Code guide

Generate UUIDs in JavaScript

Generate UUIDs in modern JavaScript with crypto.randomUUID, browser-safe fallbacks and practical validation notes.

Modern JavaScript has a built-in UUID v4 generator in secure browser contexts and recent server runtimes. Use it when available; reach for a trusted library when you need older runtime support or additional UUID versions.

Key takeaways

  • Use crypto.randomUUID() for UUID v4 in modern environments.
  • Use Web Crypto bytes for fallback code, not Math.random.
  • Use a library when you need UUID v7 across old runtimes.

For implementation context, continue with UUID v4, UUID v7, and UUID Regex. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

Modern JavaScript UUID v4

For a current browser or Node runtime, the simplest UUID v4 generator is the built-in crypto.randomUUID function. It is concise and avoids the common mistake of building identifiers with weak randomness.

const id = crypto.randomUUID();
console.log(id);

Browser fallback without Math.random

If you need a fallback, use random bytes from Web Crypto. Math.random is not appropriate for UUID generation because it is not designed for cryptographic-quality randomness.

function uuidV4() {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  bytes[6] = (bytes[6] & 0x0f) | 0x40;
  bytes[8] = (bytes[8] & 0x3f) | 0x80;

  const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0"));
  return [
    hex.slice(0, 4).join(""),
    hex.slice(4, 6).join(""),
    hex.slice(6, 8).join(""),
    hex.slice(8, 10).join(""),
    hex.slice(10, 16).join("")
  ].join("-");
}

Generating UUIDs for React forms

Generate the UUID when the record is created, not on every render. In React, a freshly generated value inside component render can change more often than you expect.

const [draftId] = useState(() => crypto.randomUUID());

Validation in JavaScript

For input validation, combine a regex with application checks. The regex confirms the shape; your backend still needs to confirm ownership and existence.

const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const isUuid = uuidPattern.test(value);

FAQ

Generate UUIDs in JavaScript questions

Should I use crypto.randomUUID or a package?

Use crypto.randomUUID for straightforward UUID v4 generation in modern runtimes. Use a package when you need older support, UUID v7 or advanced parsing tools.

Can I generate UUID v7 in JavaScript?

Yes, but built-in support is not as universal as UUID v4. Use a well-maintained library or a carefully reviewed implementation.

Is Math.random okay for UUIDs?

No. Use crypto.randomUUID or cryptographically strong random bytes.

Generate UUID in JavaScript - Browser and Node Examples