← Back to Blog
2026-03-162 min readby DevUtilz

UUID Generation and Version Differences

UUIDIdentifiersDevelopmentTutorial

UUID Generation and Version Differences

UUIDs (Universally Unique Identifiers) are 128-bit identifiers that provide a standardized way to generate unique IDs across distributed systems.

What is a UUID?

A UUID is a string like: 550e8400-e29b-41d4-a716-446655440000

It consists of 32 hexadecimal digits grouped into 5 sections:

  • 8-4-4-4-12 format
  • Ensures uniqueness across systems

UUID Versions

Version 1: Time-based

// Uses timestamp + MAC address
// Example: 6ba7b810-9dad-11d1-80b4-00c04fd430c8

Pros:

  • Sortable by creation time
  • Contains embedded timestamp

Cons:

  • Reveals when/where created
  • Requires unique MAC address

Version 4: Random

// Uses random numbers
// Example: 550e8400-e29b-41d4-a716-446655440000

Pros:

  • Privacy-friendly
  • No embedded information
  • Simple to generate

Cons:

  • Not sortable
  • Slight collision possibility

Generating UUIDs in JavaScript

// Using crypto API (modern browsers)
function generateUUIDv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// Using crypto.randomUUID() (Node 14.17+)
const uuid = crypto.randomUUID();

When to Use Each Version

| Use Case | Recommended Version | |----------|-------------------| | Database primary keys | v4 | | Session IDs | v4 | | Distributed systems | v1 or v4 | | Audit logs | v1 (sortable) | | User identifiers | v4 |

Common Mistakes

  1. Using v1 for user IDs - Reveals creation time
  2. Not using a proper library - Custom implementations may have issues
  3. Ignoring collision probability - v4 has 1 in 2^122 chance

Libraries

// uuid npm package
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // → '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

// nanoid (smaller IDs)
import { nanoid } from 'nanoid';
nanoid(); // → 'V1StGXR8_Z'

Conclusion

Use UUID v4 for most cases. It's random, private, and simple. Use v1 when you need sortable identifiers with embedded timestamps.