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.
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);