Home/Blog/Can I generate UUIDs in different programming languages?
Web Development

Can I generate UUIDs in different programming languages?

Explore UUID generation across popular programming languages, from JavaScript to Python, Java, and beyond, with practical examples and best practices.

By Inventive HQ Team
Can I generate UUIDs in different programming languages?

Understanding Universal Unique Identifiers

Universal Unique Identifiers (UUIDs), also known as Globally Unique Identifiers (GUIDs), are 128-bit numbers used to uniquely identify information in distributed systems. A UUID is represented as a 32-character hexadecimal string, typically formatted with hyphens as: 550e8400-e29b-41d4-a716-446655440000.

UUIDs are essential in modern software development for scenarios where you need to generate identifiers without relying on a central authority or database sequence. The probability of generating the same UUID twice is so astronomically low that collisions are practically impossible, making UUIDs suitable for distributed systems where different parts of an application might independently generate identifiers.

Fortunately, virtually every modern programming language has built-in or readily available libraries for generating UUIDs. Let's explore how to generate UUIDs across the most popular platforms.

JavaScript UUID Generation

Browser Environment: Modern browsers include native UUID generation through the Web Crypto API:

// Generate a random UUID
const uuid = crypto.randomUUID();
console.log(uuid); // e.g., "550e8400-e29b-41d4-a716-446655440000"

This is the simplest approach and doesn't require any external libraries.

Node.js Environment: Node.js provides UUID generation through the built-in crypto module:

const crypto = require('crypto');

// Generate UUID v4 (random)
const uuid = crypto.randomUUID();
console.log(uuid);

// For more control, use the uuid package
const { v4: uuidv4, v5: uuidv5 } = require('uuid');

const randomUuid = uuidv4();
const namespaceUuid = uuidv5('hello.example.com', uuidv5.DNS);

console.log(randomUuid);    // Random UUID
console.log(namespaceUuid); // Deterministic UUID based on name

The uuid package (installed via npm) is more feature-rich and recommended for production applications.

Python UUID Generation

Python's standard library includes comprehensive UUID support:

import uuid

# Generate UUID v4 (random)
random_uuid = uuid.uuid4()
print(random_uuid)  # e.g., 550e8400-e29b-41d4-a716-446655440000

# Generate UUID v1 (timestamp-based)
timestamp_uuid = uuid.uuid1()
print(timestamp_uuid)

# Generate UUID v5 (name-based, SHA-1)
namespace = uuid.NAMESPACE_DNS
name_based_uuid = uuid.uuid5(namespace, 'example.com')
print(name_based_uuid)

# Convert string to UUID
uuid_from_string = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
print(uuid_from_string)

Python's uuid module is part of the standard library, so no external dependencies are needed.

Java UUID Generation

Java has built-in UUID support in the java.util package:

import java.util.UUID;

// Generate a random UUID
UUID randomUuid = UUID.randomUUID();
System.out.println(randomUuid);

// Parse a UUID from string
UUID parsedUuid = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
System.out.println(parsedUuid);

// Get UUID properties
long mostSigBits = randomUuid.getMostSignificantBits();
long leastSigBits = randomUuid.getLeastSignificantBits();
int version = randomUuid.version();
int variant = randomUuid.variant();

System.out.println("Version: " + version);
System.out.println("Variant: " + variant);

Java's built-in UUID class provides everything needed for UUID generation and manipulation.

C# and .NET UUID Generation

C# and .NET use the Guid structure (GUID is Microsoft's term for UUID):

using System;

// Generate a new GUID
Guid newGuid = Guid.NewGuid();
Console.WriteLine(newGuid);

// Parse a GUID from string
Guid parsedGuid = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");
Console.WriteLine(parsedGuid);

// Empty GUID
Guid emptyGuid = Guid.Empty;
Console.WriteLine(emptyGuid);

// Check for empty
if (newGuid != Guid.Empty)
{
    Console.WriteLine("GUID is not empty");
}

// Generate with specific format
string guidString = newGuid.ToString("N"); // Without hyphens
Console.WriteLine(guidString);

The Guid structure is part of the core .NET libraries.

PHP UUID Generation

PHP doesn't have built-in UUID generation, but the ramsey/uuid library is the standard choice:

<?php

require_once 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UuidException;

// Generate UUID v4 (random)
$uuid4 = Uuid::uuid4();
echo $uuid4->toString(); // e.g., 550e8400-e29b-41d4-a716-446655440000

// Generate UUID v1 (timestamp-based)
$uuid1 = Uuid::uuid1();
echo $uuid1->toString();

// Generate UUID v5 (name-based, SHA-1)
$namespace = Uuid::NAMESPACE_DNS;
$uuid5 = Uuid::uuid5($namespace, 'example.com');
echo $uuid5->toString();

// Parse from string
$uuid = Uuid::fromString('550e8400-e29b-41d4-a716-446655440000');
echo $uuid->toString();

Install via Composer: composer require ramsey/uuid

Go UUID Generation

Go has UUID support in the google/uuid package:

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    // Generate a new UUID
    id := uuid.New()
    fmt.Println(id)

    // Generate UUID with specific version/variant
    id4, _ := uuid.NewRandom() // v4
    fmt.Println(id4)

    // Parse UUID from string
    id, _ := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
    fmt.Println(id)

    // Get UUID as string
    idString := id.String()
    fmt.Println(idString)

    // Get UUID as bytes
    bytes := id[:]
}

Install via Go modules: go get github.com/google/uuid

Ruby UUID Generation

Ruby uses the SecureRandom module or the uuidv4 gem:

require 'securerandom'

# Generate random UUID (v4)
uuid = SecureRandom.uuid
puts uuid

# For more UUID versions, use a gem
require 'uuidv4'

# Generate v4
uuid = UUIDv4.random
puts uuid

TypeScript UUID Generation

TypeScript uses the same approaches as JavaScript. For better type safety:

import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';

// Generate random UUID with type
const userId: string = uuidv4();

// Generate v5 UUID
const namespace = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // DNS namespace
const domainId: string = uuidv5('example.com', namespace);

// Type-safe UUID type
type UUID = string & { readonly __brand: 'UUID' };

function createUUID(uuid: string): UUID {
    return uuid as UUID;
}

const typedUuid: UUID = createUUID(uuidv4());

UUID Versions and When to Use Them

UUID v1 (Time-based):

  • Generated from timestamp and MAC address
  • Predictable if MAC address is known
  • Useful for systems that need sortable IDs
  • Not recommended for privacy-sensitive applications
import uuid
time_based = uuid.uuid1()

UUID v4 (Random):

  • Generated from random numbers
  • Non-deterministic and unpredictable
  • Recommended for most use cases
  • Most commonly used version
const random = crypto.randomUUID();

UUID v5 (Name-based, SHA-1):

  • Generated from namespace and name
  • Deterministic—same input always produces same output
  • Useful for generating consistent IDs for known values
  • Better for security than v1
UUID namespace = new UUID(0L, 0L); // Your namespace
UUID nameUuid = UUID.nameUUIDFromBytes("example.com".getBytes());

Best Practices for UUID Generation

1. Use v4 by default: UUID v4 (random) is appropriate for most use cases and recommended for security and privacy.

2. Use v5 for deterministic IDs: When you need to generate the same UUID for the same input consistently, use v5.

3. Avoid v1 in new code: UUID v1 has privacy implications (MAC address) and is rarely the right choice for new development.

4. Handle UUID storage: Store UUIDs as either:

  • String (16-byte text representation with hyphens or without)
  • Binary (16 bytes, more storage efficient)
  1. Consider sortability: UUID v1 is sortable by timestamp, but random v4 UUIDs are not. If you need sortability, consider ULIDs or Snowflake IDs instead.

6. Validate UUID format: Always validate UUIDs before storing them:

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

UUID vs Other Identifier Schemes

UUIDs vs Database Sequences:

  • UUIDs work in distributed systems without central coordination
  • Sequences are easier to read and more storage-efficient
  • Use UUIDs for distributed systems, sequences for single-database applications

UUIDs vs ULIDs:

  • ULIDs are sortable and timestamp-based
  • UUIDs have better collision resistance
  • Use ULIDs if you need sortability, UUIDs for general use

UUIDs vs Snowflake IDs:

  • Snowflake IDs are optimized for distributed databases
  • UUIDs are more universal and easier to implement
  • Use Snowflake IDs for Twitter/LinkedIn-scale systems, UUIDs for general applications

Conclusion

UUID generation is available across all major programming languages, either through built-in libraries or well-maintained packages. While the specific APIs differ, the underlying concepts are consistent. For most applications, UUID v4 (random) generated through the language's standard libraries is the appropriate choice. Understanding the different UUID versions and when to use each helps ensure you're using the right identifier scheme for your specific requirements. Whether you're building a simple web application or a distributed system, proper UUID generation and handling is fundamental to building robust systems.

Need Expert IT & Security Guidance?

Our team is ready to help protect and optimize your business technology infrastructure.