Code Example
// Modern browsers and Node.js 16+
const uuid = crypto.randomUUID();
console.log(uuid); // 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'
// Manual implementation (cross-browser)
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Using crypto.getRandomValues (more secure)
function secureUUID() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
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)}`;
}
// Node.js with uuid package
// npm install uuid
const { v4: uuidv4 } = require('uuid');
const id = uuidv4();
// Validate UUID format
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
uuidRegex.test(uuid); // true
Key Points: crypto.randomUUID() is the modern standard. For older browsers, use crypto.getRandomValues() or uuid package.