Reviewed 2026-09-11. Check runtime requirements before running an example.
For a random UUID v4 in a modern browser, call crypto.randomUUID(). It returns a 36-character string and needs no package. Serve the page over HTTPS or a trusted local development origin.
Choose v7 when you need a timestamp in the identifier. Use a maintained library for browser v7 generation; randomUUID() itself always returns v4. These examples target browser code, while the Node.js guide covers server imports.
Generate a UUID with Web Crypto
Feature-detect the method instead of assuming a particular browser version. The returned identifier is suitable for record IDs; authorization still belongs on the server.
if (typeof globalThis.crypto?.randomUUID !== "function") {
throw new Error("UUID generation requires a supported secure browser context");
}
const id = globalThis.crypto.randomUUID();
console.log(id);A v4 fallback using cryptographic bytes
If randomUUID is unavailable but getRandomValues exists, fill 16 bytes and set the version and variant bits. Fail explicitly when secure randomness is unavailable. Do not substitute Math.random().
function uuidV4(cryptoApi = globalThis.crypto) {
if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
if (typeof cryptoApi?.getRandomValues !== "function") {
throw new Error("Secure randomness is unavailable");
}
const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, 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)].join("-");
}
console.log(uuidV4());Generate UUID v7 in a bundled app
Install uuid with npm install uuid. The example uses its ESM exports; a bundler resolves the bare package import. Pasting this import into a plain browser script without a bundler or import map will not resolve the package.
import { v7, validate, version } from "uuid";
const id = v7();
console.assert(validate(id) && version(id) === 7);
console.log(id);Keep identifiers stable
Generate an ID when a record is created, then retain it. Generating new keys on every render can reset component state. A UUID sent by a client is untrusted: validate its format and check access to the referenced record on the server.
Frequently asked questions
- Is crypto.randomUUID() supported in all browsers?
- Feature-detect crypto.randomUUID in your target browser. It requires a secure context. If getRandomValues is available, a correctly implemented v4 fallback is possible.
- Do I need a library to generate a UUID in JavaScript?
- No. crypto.randomUUID() is built in. A library like uuid is only needed if you want versions other than v4 or broader environment support.
- Is crypto.randomUUID() random enough?
- Yes. It uses a cryptographically strong random number generator, making it suitable for IDs that should be hard to guess.
