โ† Back to Blog

How to Generate a UUID in JavaScript

2026-04-06 ยท 5 min read

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 โ†’