Back

A Practical Guide to Generating UUIDs in JavaScript

A Practical Guide to Generating UUIDs in JavaScript

Need a unique identifier for your JavaScript application? Whether you’re building a database-driven app, managing user sessions, or tracking distributed requests, UUID generation is a fundamental skill every developer needs.

This guide covers the modern approaches to JavaScript UUID generation, from the built-in crypto.randomUUID() method to the versatile uuid npm package. You’ll learn which method fits your specific use case—whether that’s a cutting-edge web app, a Node.js service, or a legacy system requiring broad compatibility.

Key Takeaways

  • Use crypto.randomUUID() for modern environments (Node.js 14.17+ and recent browsers)
  • Implement crypto.getRandomValues() for legacy browser support with cryptographic security
  • Choose the uuid npm package when you need specific UUID versions or maximum compatibility
  • Never use Math.random() for production UUIDs due to lack of cryptographic security

What is a UUID and Why Use It?

A UUID (Universally Unique Identifier) is a 128-bit identifier formatted as 36 characters: 550e8400-e29b-41d4-a716-446655440000. Also known as GUIDs, these identifiers are practically guaranteed to be unique without requiring a central authority or database coordination.

For frontend and Node.js developers, UUIDs solve critical problems:

  • Database records: Generate primary keys without auto-increment conflicts
  • Session tokens: Create unpredictable, unique session identifiers
  • File naming: Prevent naming collisions in uploaded content
  • Request tracking: Trace operations across microservices

Modern Method: crypto.randomUUID()

The crypto.randomUUID() method is the current standard for generating unique ID values in modern environments. It’s built into browsers and Node.js (14.17+), requires no dependencies, and produces cryptographically secure UUID v4 values.

Browser Implementation

const uuid = crypto.randomUUID();
console.log(uuid); // "3b99e3e0-7598-4bf8-b9c1-e915af91713c"

Node.js Implementation

import { randomUUID } from 'crypto';

const uuid = randomUUID();
console.log(uuid); // "b7e44f0a-811f-4c1c-b7f0-48d51f5dbc1f"

Browser Support: Chrome 92+, Firefox 95+, Safari 15.4+, Edge 92+
Node.js Support: Version 14.17.0+

Use crypto.randomUUID() when you need secure, random UUIDs in modern applications without external dependencies.

Fallback Method: crypto.getRandomValues()

For environments that don’t support crypto.randomUUID(), you can implement UUID v4 generation using crypto.getRandomValues(). This method works in browsers as far back as Chrome 11 and Node.js versions with the crypto module.

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = crypto.getRandomValues(new Uint8Array(1))[0];
    const v = c === 'x' ? (r & 0x0f) : ((r & 0x03) | 0x08);
    return v.toString(16);
  });
}

const uuid = generateUUID();
console.log(uuid); // "42254574-affd-47cc-9915-0ecae592351b"

This approach maintains cryptographic security while supporting older environments.

The uuid npm Package for Maximum Flexibility

The uuid npm package remains the most versatile solution for JavaScript UUID generation, especially when you need specific UUID versions or maximum compatibility.

Installation

npm install uuid

Basic Usage (UUID v4)

import { v4 as uuidv4 } from 'uuid';

const uuid = uuidv4();
console.log(uuid); // "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

Other UUID Versions

import { v1, v3, v5 } from 'uuid';

// v1: Timestamp-based (sortable)
const uuid1 = v1(); 

// v3/v5: Name-based (deterministic)
const uuid5 = v5('hello.example.com', v5.DNS);

The uuid package supports all UUID versions (v1-v5), making it ideal when you need:

  • Timestamp-based UUIDs for sortable identifiers (v1)
  • Deterministic UUIDs from namespace/name pairs (v3, v5)
  • Backward compatibility with older Node.js versions
  • React Native or other non-standard environments

When to Avoid Math.random()

While you might find UUID implementations using Math.random(), these should only be used for testing or non-secure contexts:

// ⚠️ NOT SECURE - Testing only
function testUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

Math.random() lacks cryptographic security and shouldn’t be used for production UUIDs.

Best Practices and Validation

UUID Validation

Always validate UUIDs from external sources:

function isValidUUID(uuid) {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(uuid);
}

console.log(isValidUUID('550e8400-e29b-41d4-a716-446655440000')); // true

Choosing the Right Method

  • Modern web app or Node.js 14.17+: Use crypto.randomUUID()
  • Legacy browser support needed: Implement with crypto.getRandomValues()
  • Specific UUID versions (v1, v3, v5): Use the uuid npm package
  • Maximum compatibility: Use the uuid npm package
  • Quick testing/prototypes only: Math.random() implementation

Conclusion

UUID generation in JavaScript doesn’t have to be complex. For most modern applications, crypto.randomUUID() provides a simple, secure solution. When you need broader compatibility or specific UUID versions, the uuid npm package has you covered. Just remember to avoid Math.random() for production use and validate any UUIDs from external sources.

Choose the method that matches your environment and requirements—your future self (and your team) will thank you for the clean, reliable unique identifiers throughout your codebase.

FAQs

UUID v4 uses random or pseudo-random numbers, making each ID unpredictable. UUID v5 generates deterministic IDs from a namespace and name using SHA-1 hashing, so the same input always produces the same UUID.

No, React Native doesn't support crypto.randomUUID() natively. Use the uuid npm package instead, which provides a compatible implementation that works across React Native environments.

For shorter IDs, consider using nanoid or shortid packages. They generate URL-safe unique strings that are more compact than UUIDs while maintaining sufficient uniqueness for most applications.

Yes, UUID v4 values are cryptographically random and safe to expose. However, avoid using UUID v1 in public contexts as it contains timestamp and MAC address information that could leak system details.

Complete picture for complete understanding

Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Check our GitHub repo and join the thousands of developers in our community.

OpenReplay