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

Expected output

550e8400-e29b-41d4-a716-446655440000

Related snippets

Related DuskTools