Anatomy of a UUID
xxxxxxxx-xxxx-Vxxx-Nxxx-xxxxxxxxxxxx
V is the version digit (4 or 7). N is the variant, and is always 8, 9, a or b for standard UUIDs. In a v4 UUID, the other 122 bits are random. In a v7 UUID (RFC 9562), the first 12 hex digits are the Unix time in milliseconds, followed by random bits.
| Version | Based on | Sortable | Use it for |
|---|---|---|---|
| v1 | Time + MAC address | Partly | Legacy systems; leaks the machine address |
| v4 | Random | No | General IDs that reveal nothing |
| v5 | SHA-1 of a name | No | The same ID every time for the same input |
| v7 | Time + random | Yes | Database primary keys, event IDs |
Generate a UUID in code
crypto.randomUUID(); // browser and Node 19+: v4
import { v7 } from 'uuid'; v7(); // npm package "uuid"
import uuid; uuid.uuid4() # Python
SELECT gen_random_uuid(); -- PostgreSQL 13+: v4
SELECT uuidv7(); -- PostgreSQL 18+Frequently asked questions
Should I use UUID v4 or v7?
Use v7 for database primary keys. Its first 48 bits are a millisecond timestamp, so new IDs sort in creation order and insert at the end of a B-tree index instead of at random places, which keeps indexes compact and inserts fast. Use v4 when you want an ID that reveals nothing, not even roughly when it was made.
Can two UUIDs ever be the same?
In theory, yes; in practice, no. A v4 UUID has 122 random bits. You would need to generate about 2.7 quintillion of them to have a 50% chance of a single duplicate.
Are these UUIDs secure to use as tokens?
They come from the browser’s cryptographically secure random generator (crypto.getRandomValues), so they are unpredictable. Even so, for session tokens or password reset links, prefer a purpose-built token with at least 128 random bits and an expiry.
What is the difference between a UUID and a GUID?
Nothing meaningful. GUID is Microsoft’s name for the same 128-bit identifier format.