How to Generate a UUID in JavaScript
Native Method: crypto.randomUUID()
Since Node.js 14.17.0 and modern browsers, JavaScript provides a built-in UUID v4 generation method with no external dependencies. crypto.randomUUID() uses a cryptographically secure random number generator and directly returns a UUID v4 string in RFC 4122 format. This is the currently recommended first-choice method โ simple, secure, and zero-dependency. In Node.js, import from the crypto module; in browser environments, globalThis.crypto.randomUUID() is available directly.
// Node.js (v14.17.0+)
const { randomUUID } = require('crypto');
const id = randomUUID();
console.log(id); // e.g., '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// ES Module ๅๆณ
import { randomUUID } from 'crypto';
// ๆต่งๅจ็ซฏ๏ผ็ฐไปฃๆต่งๅจ๏ผ
const id = globalThis.crypto.randomUUID();
// async ๅฝๆฐไธญไฝฟ็จ
async function createResource() {
const resourceId = crypto.randomUUID();
return { id: resourceId, createdAt: new Date() };
}
Using the uuid npm Package
The uuid package is the most popular UUID library in the JavaScript ecosystem, with over 100 million weekly downloads. It supports all UUID versions including v1, v3, v4, v5, and v7, suitable for scenarios requiring specific versions. Installation: npm install uuid. For new projects, if you only need UUID v4, prefer the built-in crypto.randomUUID(); use the uuid package when you need v5, v7, or other versions.
// npm install uuid
import { v1, v4, v5, v7 } from 'uuid';
// UUID v4 (้ๆบ)
console.log(v4()); // '110e8400-e29b-41d4-a716-446655440000'
// UUID v1 (ๆถ้ดๆณ + MAC)
console.log(v1());
// UUID v5 (ๅฝๅ็ฉบ้ด + ๅ็งฐ๏ผ็กฎๅฎๆง)
const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
console.log(v5('https://example.com', NAMESPACE));
// UUID v7 (ๆถ้ดๆๅบ๏ผ้ๅๆฐๆฎๅบไธป้ฎ)
console.log(v7());
Generating UUID in Browser Without External Libraries
If you need to generate UUID v4 in older browsers that don't support crypto.randomUUID(), you can manually implement it using crypto.getRandomValues(). This method uses cryptographically secure random numbers, which is safer than Math.random().
// ๅ
ผๅฎนๆงๆต่งๅจ็ UUID v4 ็ๆ
function generateUUID() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
// ๆ่
ๆดๆธ
ๆฐ็็ๆฌ
function uuidv4() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40; // ็ๆฌ 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // ๅไฝ
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)}`;
}
Using UUID in TypeScript
// TypeScript ็คบไพ
import { v4 as uuidv4, v7 as uuidv7 } from 'uuid';
interface User {
id: string;
name: string;
createdAt: Date;
}
function createUser(name: string): User {
return {
id: uuidv4(),
name,
createdAt: new Date(),
};
}
// ไฝฟ็จ crypto.randomUUID() - Node.js 18+ ๅ
็ฝฎ็ฑปๅๅฃฐๆ
const id: string = crypto.randomUUID();
// ็ฑปๅๅฎๅซ๏ผ้ช่ฏ UUID ๆ ผๅผ
function isUUID(str: string): boolean {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(str);
}
Best Practices in React and Vue
When using UUID in frontend frameworks, note these best practices: don't generate UUID during rendering (otherwise each re-render creates a new ID); in React, initialize once with useState or useRef; for list rendering keys, use existing IDs if data already has stable IDs rather than temporarily generated UUIDs; in Server-Side Rendering (SSR), client and server generate different UUIDs, which may cause hydration mismatch and requires special handling.
// React ็คบไพ๏ผๆญฃ็กฎๅจ็ปไปถไธญไฝฟ็จ UUID
import { useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
function TodoItem({ text }) {
// ๆญฃ็กฎ๏ผๅๅงๅไธๆฌก๏ผไธไผๆฏๆฌกๆธฒๆ้ฝๅ
const [id] = useState(() => uuidv4());
return {text};
}
// ้่ฏฏ็คบไพ๏ผๆฏๆฌกๆธฒๆ้ฝ็ๆๆฐ UUID๏ผ
// const id = uuidv4(); // ไธ่ฆ่ฟๆ ทๅ๏ผ
Performance Considerations
Generating UUID in JavaScript is not a bottleneck for most scenarios. crypto.randomUUID() performance is typically better than the uuid package (direct native API call), capable of generating millions of UUIDs per second on modern hardware. If you need to batch-generate large numbers of UUIDs (data migration, seed data initialization), use a loop or Array.from() for batch generation; for extreme performance requirements, call crypto.getRandomValues() once to get multiple random bytes, then derive multiple UUIDs from them, reducing system call count.
Try the free tool now
Use Free Tool โ