How do I create a GUID / UUID?

Learn how do i create a guid / uuid? with practical examples, diagrams, and best practices. Covers javascript, guid, uuid development techniques with visual explanations.

Generating Unique Identifiers: GUIDs and UUIDs in JavaScript

Hero image for How do I create a GUID / UUID?

Learn how to create globally unique identifiers (GUIDs/UUIDs) in JavaScript, exploring various methods and their suitability for different use cases.

Globally Unique Identifiers (GUIDs) and Universally Unique Identifiers (UUIDs) are 128-bit numbers used to uniquely identify information in computer systems. While often used interchangeably, UUID is the official standard, and GUID is Microsoft's implementation. They are crucial for tasks like database primary keys, distributed system coordination, and generating unique filenames, ensuring that each identifier is distinct across space and time.

Understanding UUID Versions

UUIDs come in several versions, each with a different generation algorithm and properties. The most common versions are v1, v3, v4, and v5. Understanding these versions helps in choosing the right one for your application.

  • UUID v1 (Time-based): Generates UUIDs based on the current timestamp and the MAC address of the computer. This ensures uniqueness but can expose the MAC address and generation time.
  • UUID v3 (Name-based, MD5): Generates UUIDs by hashing a namespace identifier and a name using MD5. This produces a consistent UUID for the same input.
  • UUID v4 (Random): Generates UUIDs using truly or pseudo-random numbers. This is the most common version for general-purpose unique ID generation as it doesn't expose system information.
  • UUID v5 (Name-based, SHA-1): Similar to v3 but uses SHA-1 hashing, offering better collision resistance than MD5.
flowchart TD
    A[Start UUID Generation] --> B{Choose Version?}
    B -->|v1 (Time/MAC)| C[Get Timestamp & MAC Address]
    B -->|v3/v5 (Name-based)| D[Hash Namespace + Name]
    B -->|v4 (Random)| E[Generate Random Bits]
    C --> F[Format UUID]
    D --> F
    E --> F
    F --> G[Return UUID]

UUID Generation Process Flow

Generating UUID v4 in JavaScript

UUID v4 is the most commonly used version for general-purpose unique identifier generation due to its simplicity and reliance on random numbers, which minimizes the risk of exposing system details. There are several ways to generate UUID v4 in JavaScript, ranging from simple custom functions to using established libraries.

Using crypto.randomUUID() (Modern Browsers/Node.js)

// Modern browsers and Node.js v14.17.0+ provide crypto.randomUUID()
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
  const uuid = crypto.randomUUID();
  console.log(`Generated UUID: ${uuid}`);
} else {
  console.warn("crypto.randomUUID() not available. Falling back to alternative.");
  // Fallback to a custom function or library if needed
}

Custom Function (Pseudo-random)

function generateUUIDv4() {
  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);
  });
}

const uuid = generateUUIDv4();
console.log(`Generated UUID: ${uuid}`);
// First, install the library: npm install uuid
// Then, import and use:
import { v4 as uuidv4 } from 'uuid';

const uuid = uuidv4();
console.log(`Generated UUID: ${uuid}`);

// For Node.js CommonJS:
// const { v4: uuidv4 } = require('uuid');
// const uuid = uuidv4();
// console.log(`Generated UUID: ${uuid}`);

Choosing the Right Method

The best method for generating UUIDs depends on your environment and requirements:

  • crypto.randomUUID(): This is the most secure and performant option for environments where it's available (modern browsers, Node.js v14.17.0+). It leverages cryptographically strong pseudo-random number generators.
  • Custom Pseudo-random Function: Suitable for environments without crypto.randomUUID() or when you need a lightweight solution without external dependencies. However, it relies on Math.random(), which is not cryptographically secure and might be less suitable for security-sensitive applications.
  • uuid Library: The gold standard for robust UUID generation. It supports all UUID versions (v1, v3, v4, v5), offers better randomness (using crypto module in Node.js or window.crypto in browsers when available, falling back to Math.random() otherwise), and handles edge cases. It's highly recommended for production applications.

1. Assess Environment

Check if crypto.randomUUID() is available in your target environment (e.g., typeof crypto !== 'undefined' && crypto.randomUUID).

2. Prioritize crypto.randomUUID()

If available, use crypto.randomUUID() for its security and native performance. This is the preferred method.

3. Consider the uuid Library

If crypto.randomUUID() is not available or you need specific UUID versions (v1, v3, v5), or require a more robust solution with better cross-environment compatibility, integrate the uuid library.

4. Use Custom Function as Last Resort

Only use a custom Math.random() based function for non-critical applications where bundle size is extremely sensitive and security is not a primary concern.