JavaScript

UUID v4 Generator

by @admin
10h ago
Apr 28, 2026
Public
Generates a RFC 4122 compliant version-4 UUID. Uses crypto.randomUUID() in modern environments (Node 14.17+, all modern browsers) and falls back to a Math.random()-based implementation for older runtimes. The fallback is suitable for non-security-critical IDs such as UI element keys and local correlation IDs.
JavaScript
function uuid() {
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  // Fallback (not cryptographically secure)
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
  });
}

// Usage
console.log(uuid()); // e.g. '3b1c9a4f-d82e-4c3b-a7f1-2e9d5b6f8c0e'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.