Working with UUIDs in JavaScript and Node.js
JavaScript and Node.js offer multiple ways to generate and work with UUIDs — from the browser's built-in crypto.randomUUID() to the popular uuid npm package. This guide covers all the modern approaches.
The Built-In crypto.randomUUID()
The simplest and most direct way to generate a UUID v4 in modern JavaScript is crypto.randomUUID(). Available in all major browsers and Node.js 19+:
const uuid = crypto.randomUUID();
console.log(uuid); // "3a2e6b1f-8d4c-4e5f-a6b7-123456789abc" This method uses a cryptographically secure random number generator (CSPRNG), making it suitable for production use. It always generates UUID v4.
The uuid npm Package
For more flexibility — including v1, v3, v4, v5, v6, and v7 UUIDs — the uuid npm package is the go-to choice:
import { v1, v3, v4, v5, v7 } from 'uuid';
// Time-based UUID (v1)
const timeBased = v1(); // e.g., "c1c4f0e0-3a2b-11ee-be56-0242ac120002"
// Random UUID (v4)
const random = v4(); // e.g., "3a2e6b1f-8d4c-4e5f-a6b7-123456789abc"
// UUID v7 (time-ordered, sortable)
const sortable = v7(); // e.g., "018e1d5c-8e5e-7f6a-b3c4-d5e6f7a8b9c0"
// Namespace-based UUID (v5)
const NAMESPACE_DNS = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
const dnsBased = v5('example.com', NAMESPACE_DNS); Validating UUIDs
The uuid package provides validation:
import { validate, version } from 'uuid';
validate('not-a-uuid'); // false
validate('3a2e6b1f-8d4c-4e5f-a6b7-123456789abc'); // true
version('3a2e6b1f-8d4c-4e5f-a6b7-123456789abc'); // 4
version('c1c4f0e0-3a2b-11ee-be56-0242ac120002'); // 1
version('018e1d5c-8e5e-7f6a-b3c4-d5e6f7a8b9c0'); // 7 Formatting Raw UUID Strings
When working with raw 32-character hex strings from databases or APIs, you may need to format them yourself:
function formatUUID(raw) {
const hex = raw.replace(/[^a-fA-F0-9]/g, '');
if (hex.length !== 32) return null;
return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16) + '-' + hex.slice(16, 20) + '-' + hex.slice(20);
}
formatUUID('3a2e6b1f8d4c4e5fa6b7123456789abc');
// "3a2e6b1f-8d4c-4e5f-a6b7-123456789abc" Browser vs Node.js Considerations
| Method | Browser | Node.js |
|---|---|---|
crypto.randomUUID() | All modern browsers | Node.js 19.0+ |
uuid npm package | Via bundlers | All versions |
Web Crypto API | All modern browsers | Node.js 15.0+ |
Security Note
Never use Math.random() to generate UUIDs. It is not cryptographically secure and produces predictable values. Always use crypto.randomUUID() or the uuid package, both of which use CSPRNGs.