How to Generate UUIDs in JavaScript, Python, Java, and Go
Meta Description: Generate UUIDs in any language. Copy-paste code examples for JavaScript, Python, Java, Go, Rust, PHP, and command line UUID generation.
Need a UUID in your code? Here's how to generate them in every major programming language—with copy-paste examples you can use right now.
JavaScript / TypeScript
Built-in: crypto.randomUUID() (Recommended)
Available in browsers (Chrome 92+, Firefox 95+, Safari 15.4+) and Node.js 16+:
// Generate a v4 UUID
const id = crypto.randomUUID();
console.log(id);
// 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
Node.js crypto module
import { randomUUID } from 'crypto';
const id = randomUUID();
console.log(id);
// 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
uuid package (v4, v1, v7)
For more control or older environments:
npm install uuid
import { v4 as uuidv4, v1 as uuidv1, v7 as uuidv7 } from 'uuid';
// v4 - random
const randomId = uuidv4();
// 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
// v1 - timestamp + MAC
const timeId = uuidv1();
// '6ba7b810-9dad-11d1-80b4-00c04fd430c8'
// v7 - sortable timestamp (uuid v9+)
const sortableId = uuidv7();
// '0184e0e9-5b50-7dd8-8a0b-9e5d8a8b3f2a'
// Validate
import { validate } from 'uuid';
validate(randomId); // true
validate('not-a-uuid'); // false
TypeScript Types
import { v4 as uuidv4 } from 'uuid';
// UUID is just a string
const id: string = uuidv4();
// Type-safe alternative
type UUID = `${string}-${string}-${string}-${string}-${string}`;
function createUser(id: UUID, name: string) {
// ...
}
Python
Built-in uuid module (Recommended)
import uuid
# v4 - random (most common)
random_id = uuid.uuid4()
print(random_id)
# f47ac10b-58cc-4372-a567-0e02b2c3d479
# v1 - timestamp + MAC
time_id = uuid.uuid1()
print(time_id)
# 6ba7b810-9dad-11d1-80b4-00c04fd430c8
# Convert to string
str_id = str(random_id)
hex_id = random_id.hex # without hyphens
# Parse from string
parsed = uuid.UUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')
# Validate
def is_valid_uuid(val):
try:
uuid.UUID(str(val))
return True
except ValueError:
return False
uuid7 package (v7 support)
pip install uuid7
import uuid7
# v7 - sortable timestamp
sortable_id = uuid7.uuid7()
print(sortable_id)
# 0184e0e9-5b50-7dd8-8a0b-9e5d8a8b3f2a
uuid-utils package (All versions, faster)
pip install uuid-utils
from uuid_utils import uuid4, uuid7
id_v4 = uuid4()
id_v7 = uuid7()
Java
java.util.UUID (Built-in)
import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
// v4 - random
UUID randomId = UUID.randomUUID();
System.out.println(randomId);
// f47ac10b-58cc-4372-a567-0e02b2c3d479
// Parse from string
UUID parsed = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479");
// Get components
long mostSig = randomId.getMostSignificantBits();
long leastSig = randomId.getLeastSignificantBits();
// Version
int version = randomId.version(); // 4
// Compare
boolean equal = randomId.equals(parsed);
}
}
UUID v7 (com.github.f4b6a3:uuid-creator)
<!-- Maven -->
<dependency>
<groupId>com.github.f4b6a3</groupId>
<artifactId>uuid-creator</artifactId>
<version>5.3.3</version>
</dependency>
import com.github.f4b6a3.uuid.UuidCreator;
// v7 - sortable timestamp
UUID sortableId = UuidCreator.getTimeOrderedEpoch();
// v1 - timestamp + MAC
UUID timeId = UuidCreator.getTimeBased();
// v4 - random
UUID randomId = UuidCreator.getRandomBased();
Go
google/uuid package (Recommended)
go get github.com/google/uuid
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
// v4 - random
id := uuid.New()
fmt.Println(id)
// f47ac10b-58cc-4372-a567-0e02b2c3d479
// String conversion
str := id.String()
// Parse from string
parsed, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
if err != nil {
panic(err)
}
// Validate
_, err = uuid.Parse("not-a-uuid")
if err != nil {
fmt.Println("Invalid UUID")
}
// v1 - timestamp + MAC
v1, _ := uuid.NewUUID()
// v7 - sortable timestamp (uuid v2+)
v7, _ := uuid.NewV7()
}
Rust
uuid crate
# Cargo.toml
[dependencies]
uuid = { version = "1.4", features = ["v4", "v7"] }
use uuid::Uuid;
fn main() {
// v4 - random
let id = Uuid::new_v4();
println!("{}", id);
// f47ac10b-58cc-4372-a567-0e02b2c3d479
// v7 - sortable timestamp
let id_v7 = Uuid::now_v7();
// Parse from string
let parsed = Uuid::parse_str("f47ac10b-58cc-4372-a567-0e02b2c3d479")
.expect("Invalid UUID");
// String conversion
let str_id = id.to_string();
let hyphenated = id.hyphenated().to_string();
let simple = id.simple().to_string(); // no hyphens
}
PHP
Built-in (PHP 8.1+)
<?php
// v4 - random (no external dependencies)
function uuid4(): string {
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Version 4
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Variant
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
echo uuid4();
// f47ac10b-58cc-4372-a567-0e02b2c3d479
ramsey/uuid (Full-featured)
composer require ramsey/uuid
<?php
use Ramsey\Uuid\Uuid;
// v4 - random
$uuid = Uuid::uuid4();
echo $uuid->toString();
// f47ac10b-58cc-4372-a567-0e02b2c3d479
// v1 - timestamp + MAC
$uuid1 = Uuid::uuid1();
// v7 - sortable timestamp
$uuid7 = Uuid::uuid7();
// Parse
$parsed = Uuid::fromString('f47ac10b-58cc-4372-a567-0e02b2c3d479');
// Validate
$isValid = Uuid::isValid('f47ac10b-58cc-4372-a567-0e02b2c3d479'); // true
C# / .NET
System.Guid (Built-in)
using System;
// Generate v4 UUID (Microsoft calls it GUID)
Guid id = Guid.NewGuid();
Console.WriteLine(id);
// f47ac10b-58cc-4372-a567-0e02b2c3d479
// String conversion
string str = id.ToString();
string noDashes = id.ToString("N"); // f47ac10b58cc4372a5670e02b2c3d479
// Parse
Guid parsed = Guid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479");
// TryParse for validation
bool isValid = Guid.TryParse("f47ac10b-58cc-4372-a567-0e02b2c3d479", out _);
Command Line
uuidgen (macOS, Linux)
# Generate v4 UUID
uuidgen
# F47AC10B-58CC-4372-A567-0E02B2C3D479
# Lowercase (pipe through tr)
uuidgen | tr '[:upper:]' '[:lower:]'
# f47ac10b-58cc-4372-a567-0e02b2c3d479
# Generate multiple
for i in {1..10}; do uuidgen; done
Python one-liner
python -c "import uuid; print(uuid.uuid4())"
Node.js one-liner
node -e "console.log(require('crypto').randomUUID())"
Validation Regex
For validating UUIDs in your code:
// JavaScript
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isValidUUID(str) {
return UUID_REGEX.test(str);
}
# Python
import re
UUID_PATTERN = re.compile(
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
re.IGNORECASE
)
def is_valid_uuid(s):
return bool(UUID_PATTERN.match(s))
Generate UUIDs Online
Don't want to write code? Use our UUID generator:
- Generate v1, v4, and v7 UUIDs
- Bulk generation up to 1000
- Copy with one click
- No installation needed
FAQ
Which library should I use for production?
Use built-in libraries when possible (JavaScript crypto.randomUUID, Python uuid, Java UUID, Go google/uuid). They're well-tested and don't add dependencies.
How do I generate UUIDs without dependencies?
Every example above has a built-in option. JavaScript, Python, Java, Go, C#, and PHP all have native UUID support.
Are UUIDs thread-safe to generate?
Yes. All standard library implementations use thread-safe random number generators. You can generate UUIDs from multiple threads without coordination.
How do I store UUIDs in databases?
- PostgreSQL: Native
UUIDtype - MySQL:
BINARY(16)orCHAR(36) - SQLite:
TEXTorBLOB(16) - MongoDB: Native
UUIDtype
Can I use UUIDs as passwords or tokens?
UUIDs are unique but not secret. For security tokens, use cryptographically secure random bytes (e.g., secrets.token_urlsafe(32) in Python). UUIDs are fine for session IDs if combined with proper session security.
Related Tools:
- UUID Generator — Generate UUIDs instantly
- UUID Validator — Check UUID format
- Bulk UUID Generator — Generate thousands at once