Generate UUID with crypto.randomUUID
Create a UUID v4 using the Web Crypto API.
Code
JavaScript
// Modern (Node 19+, browsers)
const uuid = crypto.randomUUID();
console.log(uuid); // "550e8400-e29b-41d4-a716-446655440000"
// Fallback
function uuidFallback() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}Line-by-line explanation
- 1.crypto.randomUUID() returns a standard UUID v4.
- 2.Fallback uses Math.random (less secure).
- 3.Replace x with random hex, y with 8/9/a/b.
Expected output
550e8400-e29b-41d4-a716-446655440000