Generate a UUID v7 string or write the bytes into a buffer.UUID v7 is a time-ordered UUID that embeds a Unix timestamp in milliseconds, making IDs naturally sortable by creation time. Ideal for database primary keys where chronological ordering improves index performance.
31-bit sequence number for monotonic ordering within the same millisecond.When not provided, automatically derived from random bytes or incremented from module state.
const id = uuidv7()const ts = uuidv7.timestamp(id)console.log(new Date(ts))// => Date object representing when the UUID was createdconsole.log(Date.now() - ts)// => Milliseconds elapsed since UUID creation
UUID v7 maintains module-level state to ensure IDs are monotonically increasing even when generated within the same millisecond:
// All called within the same millisecondconst id1 = uuidv7() // seq = random valueconst id2 = uuidv7() // seq = incrementedconst id3 = uuidv7() // seq = incremented again// Guaranteed to be in orderconsole.log(id1 < id2 && id2 < id3) // true
Important: This module-level state persists across calls:
In serverless/edge functions with warm starts, state persists between invocations
For isolated state, pass explicit msecs and seq via options
Tests should mock Date.now() or provide explicit options for deterministic behavior
Efficiently write multiple UUIDs to a pre-allocated buffer:
const buffer = new Uint8Array(64) // Space for 4 UUIDsuuidv7(undefined, buffer, 0) // First UUID at offset 0uuidv7(undefined, buffer, 16) // Second UUID at offset 16uuidv7(undefined, buffer, 32) // Third UUID at offset 32uuidv7(undefined, buffer, 48) // Fourth UUID at offset 48
Bytes 0-5: 48-bit timestamp (milliseconds since Unix epoch)Byte 6: Version (7) + 4 bits of sequenceByte 7: 8 bits of sequenceByte 8: Variant (10xx) + 6 bits of sequenceByte 9: 8 bits of sequenceBytes 10-15: Random data
export type UuidV7Options = { /** * 16 bytes of random data to use for UUID generation. * Note: Several bytes will be overwritten with timestamp, version, and variant data. */ random?: Uint8Array msecs?: number seq?: number}export type UuidV7 = { (): string <TBuf extends Uint8Array = Uint8Array>(options: UuidV7Options | undefined, buf: TBuf, offset?: number): TBuf (options?: UuidV7Options, buf?: undefined, offset?: number): string toBytes(id: string): Uint8Array fromBytes(bytes: Uint8Array): string timestamp(id: string): number isValid(id: unknown): id is string /** The nil UUID (all zeros) */ NIL: string /** The max UUID (all ones) */ MAX: string}