How to Generate UUID v4 in Node.js, Python, and Go
UUID v4 (Universally Unique Identifier, version 4) is the go-to format for generating unique identifiers without central coordination. With 122 bits of randomness, the probability of collision is negligible for any practical application.
A UUID v4 looks like this:
9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6dIt follows the format: 8-4-4-4-12 hexadecimal characters separated by hyphens. The "4" in the third group indicates the version, and the first digit of the fourth group (8, 9, a, or b) indicates the variant.
Node.js
Since Node.js 14.17.0, crypto.randomUUID() is available natively — no package required:
const { randomUUID } = require('crypto');
const id = randomUUID();
console.log(id); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// In ESM / modern Node.js
import { randomUUID } from 'crypto';
const id = randomUUID();For older Node.js or browser environments, or when you need v1/v5 support, use the uuid package:
const { v4: uuidv4 } = require('uuid');
const id = uuidv4();Python
Python's standard library includes the uuid module — no installation needed:
import uuid
# Generate a UUID v4
id = uuid.uuid4()
print(str(id)) # '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
print(id.hex) # '9b1deb4d3b7d4bad9bdd2b0d7b3dcb6d' (no hyphens)
print(int(id)) # 128-bit integer representation
# As a string directly
id_str = str(uuid.uuid4())Go
Install the github.com/google/uuid package (the de facto standard in Go):
go get github.com/google/uuidpackage main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
// Generate v4 UUID
id := uuid.New()
fmt.Println(id.String()) // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// Or using NewRandom() with error handling
id, err := uuid.NewRandom()
if err != nil {
log.Fatal(err)
}
fmt.Println(id)
}When to Use UUID vs Other ID Formats
| Use Case | Recommendation |
|---|---|
| Database primary key (single DB) | Auto-increment (simpler, sortable) |
| Distributed system / generated client-side | UUID v4 |
| Deterministic from input | UUID v5 |
| Sortable, time-ordered IDs | ULID or UUID v7 (draft) |
| Short public IDs | Nanoid or Base62-encoded UUID |
For most web applications generating database records server-side, UUID v4 is the right default. If you need time-sortable IDs for time-series workloads, consider ULID.
Try our UUID Generator to generate RFC 4122 compliant UUIDs — v1, v4, and v5 — directly in your browser.