Skip to content
uencoder
TUTORIAL

How to Generate UUIDs

Create universally unique identifiers (UUIDs/GUIDs) in various versions.

Problem

You need a unique identifier for a record, session, or event that is guaranteed unique without central coordination.

Prerequisites

  • Understanding of unique identifiers
  • Knowledge of UUID versions

Steps

  1. 1. Choose the UUID version

    Version 4 (random) is the most common — it uses random bits and has an extremely low collision probability. Version 7 is time-ordered, useful for databases. Version 5 is deterministic (name-based with SHA-1). Version 1 is time-based with a node ID.

    Input
    version: 4 (random)
    Output
    version selected
  2. 2. Generate the UUID

    Generate a UUID of the chosen version. A v4 UUID has the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where y is 8, 9, a, or b. The generation uses a cryptographically secure RNG for v4. The output is a 36-character string with hyphens.

    Input
    generate v4
    Output
    550e8400-e29b-41d4-a716-446655440000
  3. 3. Use and store the UUID

    Use the UUID as a unique key for database records, session IDs, or event identifiers. UUIDs are 128 bits, providing sufficient uniqueness for virtually all applications. Store as a UUID type in databases (more efficient than string) or as a 36-character string.

    Input
    UUID for database record
    Output
    unique key assigned

Expected result

A valid UUID in the specified version, with the correct format and version bits.

Common errors

Using Math.random for UUID generation
Math.random is not cryptographically secure. Use crypto.randomUUID() or a CSPRNG for v4 UUIDs to ensure unpredictability.
UUID stored as VARCHAR(36) when a native type exists
Many databases have a native UUID type that is more efficient (16 bytes vs 37 characters) and indexed faster. Use the native type when available.

Troubleshooting

  • If UUIDs collide (extremely unlikely for v4), verify the RNG is working correctly.
  • For time-ordered UUIDs (v7), ensure the clock is monotonic to avoid ordering issues.

Security limits

  • UUID v4 values are unpredictable and suitable for session tokens. However, they are not cryptographically strong — use a dedicated token generator for security-critical purposes.
  • All generation is local.

Related tools

Related tasks

Ready to run it?

References