How to Generate a UUID in JavaScript, Java, and Python

Last updated: October 9, 2026

A UUID (Universally Unique Identifier) is a 128-bit identifier defined by RFC 9562. It is usually written as 36 characters in 8-4-4-4-12 form, such as 3f2c9e5a-7b4d-4e2a-9c1f-8d3b6a2e4f51. UUIDs let independent systems create unique IDs without a central coordinator, which is why they show up everywhere from database primary keys to request tracing.

Generating a UUID in JavaScript

Modern browsers and Node.js ship crypto.randomUUID(), which returns a UUID v4. No library is required. It works in browsers in secure contexts (HTTPS or localhost) and in Node.js 14.17 and later.

// JavaScript (browsers, Node.js 14.17+)
const id = crypto.randomUUID();
console.log(id); // e.g. "3f2c9e5a-7b4d-4e2a-9c1f-8d3b6a2e4f51"

Generating a UUID in Java

java.util.UUID.randomUUID() generates a UUID v4 out of the box. For UUID v7 (time-ordered, recommended for database keys), use the popular uuid-creator library, since the JDK does not yet ship a built-in v7 generator.

// Java
import java.util.UUID;

UUID id = UUID.randomUUID(); // UUID v4

// UUID v7 with the uuid-creator library (com.github.f4b6a3:uuid-creator)
import com.github.f4b6a3.uuid.UuidCreator;
UUID ordered = UuidCreator.getTimeOrderedEpoch();

Generating a UUID in Python

The standard library has covered UUID v4 for years. Python 3.14 added built-in support for UUID v7 (uuid.uuid7()), matching the time-ordered format from RFC 9562.

# Python
import uuid

print(uuid.uuid4())  # UUID v4
print(uuid.uuid7())  # UUID v7 (Python 3.14+)

UUID v4 vs UUID v7

UUID v4UUID v7
Generation122 random bits48-bit millisecond timestamp + random bits
OrderingNone (uniformly random)Time-ordered (sorts by creation time)
Database indexesRandom inserts cause B-tree page splitsSequential inserts, fewer page splits
Best forTokens, anonymous IDs, anything that must be unguessablePrimary keys, event logs, sortable IDs

The trade-off: v7 values reveal when they were created, so do not use them where IDs must be unguessable. Our UUID v4 vs v7 guide goes deeper with more code examples.

Need UUIDs right now? Use the free UUID Generator โ€” it generates up to 50 UUID v4 values per click, entirely in your browser.

FAQ

What is the difference between UUID v4 and v7?

UUID v4 is fully random, which makes it ideal for tokens and anonymous IDs. UUID v7 is time-ordered: it embeds a millisecond timestamp, so values sort roughly by creation time and cause fewer page splits in B-tree database indexes.

Is crypto.randomUUID() secure?

Yes. It draws from the browser or Node.js cryptographically secure random number generator and returns UUID v4 values. It requires a secure context (HTTPS or localhost).

Do UUIDs ever collide?

UUID v4 has 122 random bits, so collisions are theoretically possible but practically negligible when a secure random source is used.