How to Generate a UUID in JavaScript, Python, Go, Rust and More
UUID (Universally Unique Identifier) generation is a solved problem in every major language — but the right way to do it varies. This guide covers copy-paste ready snippets for JavaScript, TypeScript, Node.js, Python, Go, Rust, PHP, Java, C#, and the command line.
What Is a UUID?
A UUID is a 128-bit identifier formatted as 32 hexadecimal digits in 5 groups separated by hyphens: f47ac10b-58cc-4372-a567-0e02b2c3d479. The format is defined by RFC 4122 and is designed to be unique across time and space without requiring a central authority to issue them.
The two most common versions are:
- UUID v4 — randomly generated. 122 bits of randomness. The default choice for most use cases: database primary keys, session IDs, request tracing, file names.
- UUID v1 — timestamp-based. Encodes the current time and the MAC address of the machine. Useful when you need sortable IDs or need to trace when a record was created. Less common due to MAC address privacy concerns.
The collision probability of UUID v4 is astronomically low — you'd need to generate about 2.7 quintillion UUIDs to have a 50% chance of a single collision. For practical purposes, treat them as globally unique.
UUID Generation by Language
Jump to your language: JavaScript (Browser) · TypeScript · Node.js · Python · Go · Rust · PHP · Java · C# · Command Line
JavaScript (Browser)
// Built-in — no dependencies needed
const uuid = crypto.randomUUID();
console.log(uuid); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"TypeScript
// Built-in in modern runtimes — no dependencies needed
const uuid: string = crypto.randomUUID();
console.log(uuid);Node.js
// Node 14.17+ — built-in, no install needed
const { randomUUID } = require('crypto');
const uuid = randomUUID();
console.log(uuid);
// ESM / Node 19+
import { randomUUID } from 'crypto';
const uuid = randomUUID();
// With the 'uuid' package (older Node or more control)
// npm install uuid
import { v4 as uuidv4, v1 as uuidv1 } from 'uuid';
console.log(uuidv4()); // random
console.log(uuidv1()); // timestamp-basedPython
import uuid
# v4 — random
print(uuid.uuid4()) # UUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')
print(str(uuid.uuid4())) # as string
# v1 — timestamp-based
print(uuid.uuid1())
# Without hyphens
print(uuid.uuid4().hex) # 'f47ac10b58cc4372a5670e02b2c3d479'Go
// go get github.com/google/uuid
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
// v4 — random
id := uuid.New()
fmt.Println(id.String())
// v4 with error handling
id2, err := uuid.NewRandom()
if err != nil {
panic(err)
}
fmt.Println(id2)
// v1 — timestamp-based
id3, _ := uuid.NewUUID()
fmt.Println(id3)
}Rust
# Cargo.toml
# [dependencies]
# uuid = { version = "1", features = ["v4", "v1"] }
use uuid::Uuid;
fn main() {
// v4 — random
let id = Uuid::new_v4();
println!("{}", id); // f47ac10b-58cc-4372-a567-0e02b2c3d479
println!("{}", id.simple()); // without hyphens
// Parse an existing UUID
let parsed = Uuid::parse_str("f47ac10b-58cc-4372-a567-0e02b2c3d479").unwrap();
println!("{}", parsed);
}PHP
<?php
// PHP 8.1+ — ramsey/uuid is the standard library
// composer require ramsey/uuid
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4()->toString();
echo $uuid; // f47ac10b-58cc-4372-a567-0e02b2c3d479
// v1 — timestamp-based
$uuid1 = Uuid::uuid1()->toString();
echo $uuid1;
// Without a library (PHP 7+)
function generateUUID(): string {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}Java
import java.util.UUID;
// Built-in — no dependencies needed
UUID uuid = UUID.randomUUID();
System.out.println(uuid); // f47ac10b-58cc-4372-a567-0e02b2c3d479
System.out.println(uuid.toString()); // same, as string
// Without hyphens
String clean = uuid.toString().replace("-", "");
System.out.println(clean);
// Parse an existing UUID
UUID parsed = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479");C#
using System;
// Built-in — no dependencies needed
Guid uuid = Guid.NewGuid();
Console.WriteLine(uuid); // f47ac10b-58cc-4372-a567-0e02b2c3d479
Console.WriteLine(uuid.ToString("N")); // without hyphens
Console.WriteLine(uuid.ToString("B")); // with braces {f47ac10b-...}
// Parse
Guid parsed = Guid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479");Command Line
# macOS / Linux (uuidgen is built-in)
uuidgen
uuidgen | tr '[:upper:]' '[:lower:]' # lowercase
# Linux with util-linux
uuidgen -r # random (v4)
uuidgen -t # time-based (v1)
# Python one-liner (cross-platform)
python3 -c "import uuid; print(uuid.uuid4())"
# Node.js one-liner
node -e "console.log(crypto.randomUUID())"UUID v4 vs v1: Which Should You Use?
| UUID v4 | UUID v1 | |
|---|---|---|
| Generation | Random | Timestamp + MAC address |
| Sortable | No | Yes (chronological) |
| Privacy | Safe | Exposes MAC address |
| Database index perf. | Poor (random inserts) | Better (sequential) |
| Use case | IDs, tokens, filenames | Audit logs, time-ordered records |
Common Questions About UUIDs
Are UUIDs case-sensitive?
No. F47AC10B-58CC-4372-A567-0E02B2C3D479 and f47ac10b-58cc-4372-a567-0e02b2c3d479 are the same UUID. The RFC 4122 spec recommends lowercase, but most databases and libraries handle both. Pick one convention and stick with it — comparing a lowercase UUID against an uppercase one as strings will fail.
Should I store UUIDs with or without hyphens?
With hyphens is the standard format and the most portable. Without hyphens (32 hex chars) saves 4 bytes per value and can be slightly faster to index in some databases. If you're storing in a dedicated UUID column type (PostgreSQL, MySQL 8+), the database handles the format internally — use the standard format in your application code.
Are UUIDs good as database primary keys?
UUID v4 primary keys cause index fragmentation in B-tree indexes because the values are random and non-sequential. This impacts insert performance at high volume. Solutions: use UUID v7 (sequential random, RFC 9562), use ULID, or use a database sequence for the primary key and UUID as a separate public identifier. UUID v1 avoids this problem but at the cost of MAC address exposure.
What's the difference between UUID and GUID?
None — GUID (Globally Unique Identifier) is Microsoft's name for the same concept. They follow the same RFC 4122 format. C# uses Guid, SQL Server uses uniqueidentifier, everything else typically says UUID.
Generate UUIDs Online
If you need to quickly generate one or more UUIDs without writing code — for testing, config files, or database seeds — the UUID Generator on DevEssentials generates UUID v4 and v1 in bulk, with copy-to-clipboard. No login, 100% client-side.
Need UUIDs now? Generate UUID v4 and v1 online →