Generate UUID
Create unique identifiers
Generates RFC4122 version 4 compliant UUIDs (Universally Unique Identifiers). Uses crypto.randomUUID() when available (modern browsers) with a fallback implementation for older environments. Essential for creating unique keys, session IDs, or any scenario requiring guaranteed unique identifiers.
function generateUUID(): string {
// Modern browsers support crypto.randomUUID()
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
return crypto.randomUUID();
}
// Fallback for older browsers
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);
});
}
// Usage
const id = generateUUID();
console.log(id); // "550e8400-e29b-41d4-a716-446655440000"