Random UUIDs with uuid v4
A version 4 UUID is built from random bytes and is the usual choice for ids of records, requests and keys.
How it works
- Call v4(). Import
v4(renameduuidv4) and call it with no arguments. Each call returns a new UUID string, used here as an id for each todo. [1] - Random source. The package fills the random bytes from the platform
cryptoAPI. Therngoption lets you pass your own function; here it callscrypto.getRandomValuesdirectly. [1] - Fixed bytes for tests. Passing
randomwith 16 fixed bytes gives the same UUID every run, which is handy in tests.getRandomValuesis the browser call that fills a typed array with random numbers. [2]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { v4 as uuidv4 } from 'uuid'
// Each call returns a new random UUID string
console.log('v4 #1:', uuidv4())
console.log('v4 #2:', uuidv4())
console.log('v4 #3:', uuidv4())
// Give every record its own id
const todos = ['Write docs', 'Ship release', 'Reply to issues'].map((title) => ({ id: uuidv4(), title }))
for (const t of todos) console.log(`todo "${t.title}" ->`, t.id)
// rng option: a function that returns 16 random bytes
const rng = () => crypto.getRandomValues(new Uint8Array(16))
console.log('with rng option:', uuidv4({ rng }))
// random option: fixed bytes always give the same UUID
const random = Uint8Array.of(
0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,
0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36
)
console.log('with fixed random bytes:', uuidv4({ random }))
console.log('string length:', uuidv4().length)
Run it a few times: the plain v4() lines change, the fixed-bytes line stays 109156be-c4fb-41ea-b1b4-efe1671c5836. Code written by AgentGid [1].
Run it a few times: the plain v4() lines change, the fixed-bytes line stays 109156be-c4fb-41ea-b1b4-efe1671c5836. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with uuid 14.0.3. Needs WebGL.
More uuid examples
Time-based UUIDs with uuid v7 Name-based UUIDs with uuid v5 Validating UUIDs with uuid Converting UUIDs to bytes with uuid
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.