Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/uuids/javascript$ _

Generate UUIDs in JavaScript

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: JavaScript

What: Generate UUIDs in JavaScript using the native <code>crypto.randomUUID()</code> API (modern browsers/Node.js 15.6+) or the popular <code>uuid</code> npm package for broader support.

Try it: Use our interactive Uuids generator or integrate this code into your JavaScript application.

Generate UUIDs in JavaScript using the native crypto.randomUUID() API (modern browsers/Node.js 15.6+) or the popular uuid npm package for broader support. Looking for other languages? Check our code examples in PHP , Python , Java , C# , C++ , Ruby and Go or use our interactive web generator.

JavaScript Code Example

// Modern browsers and Node.js 15.6+ (native API)
const uuid = crypto.randomUUID();
console.log(uuid);  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

// Using uuid npm package (install: npm install uuid)
import { v4 as uuidv4, v5 as uuidv5, v7 as uuidv7 } from 'uuid';

// UUID v4 (random)
const uuid4 = uuidv4();
console.log(uuid4);  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

// UUID v7 (timestamp-ordered)
const uuid7 = uuidv7();
console.log(uuid7);  // Example: 018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b

// UUID v5 (namespaced)
const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // DNS namespace
const name = 'example.com';
const uuid5 = uuidv5(name, NAMESPACE);
console.log(uuid5);  // Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

// Validate UUID
import { validate, version } from 'uuid';
if (validate(uuid4)) {
    console.log('Version:', version(uuid4));  // Outputs: 4
}

[EXPLANATION]

Native crypto.randomUUID() generates UUID v4 with zero dependencies. The uuid npm package provides more options including v7 (timestamp-ordered, best for databases). Use v7 for sortable IDs.

Expected Output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b
cfbff0d1-9375-5685-968c-48ce8b15ae17
4

Common Use Cases

  • React/Vue component unique keys
  • MongoDB document IDs
  • WebSocket connection identifiers
  • Client-side request tracking
  • IndexedDB primary keys
  • Microservices correlation IDs

Important Notes

  • crypto.randomUUID() requires Node.js 15.6+ or modern browsers
  • For older environments, use uuid npm package
  • UUID v7 is best for databases (sortable by creation time)
  • uuid package has 50M+ weekly npm downloads

Try Our Interactive Generator

Don't want to write code? Use our free web-based Uuids generator with instant results.

TRY UUIDS GENERATOR →