uniku
Reference

KSUID

Time-ordered identifiers with a 128-bit random payload.

KSUID combines a timestamp with a large random payload. Choose it for high-volume distributed systems that need chronological order and a 27-character URL-safe string.

import { ksuid } from 'uniku/ksuid'

const eventId = ksuid()
// '3GPXkrDipgmtLBpkbfrWSPz8a4F' (string)

Generated API reference

Public methods

Read source

Generate a KSUID string or write the bytes into a buffer. Also includes helpers to convert to and from byte arrays.

ksuid

Generate a time-ordered KSUID string.

ksuid(): string

Generate a KSUID with explicit options or write its 20 canonical bytes into a caller-owned buffer.

ksuid<TBuf extends Uint8Array = Uint8Array>(options: KsuidOptions | undefined, buf: TBuf, offset?: number): TBuf

Generate a KSUID string with optional timestamp or random payload bytes.

ksuid(options?: KsuidOptions, buf?: undefined, offset?: number): string

KsuidOptions

random?

16 bytes of random data to use for KSUID payload.

Uint8Array
secs?

Timestamp in seconds since Unix epoch. Defaults to Math.floor(Date.now() / 1000). KSUID natively uses second precision.

number
Exampleksuid()// => '3GPXkrDipgmtLBpkbfrWSPz8a4F'
toBytes

Convert a KSUID string to its canonical 20-byte representation.

toBytes(id: string): Uint8Array
Exampleksuid.toBytes('3GPXkrDipgmtLBpkbfrWSPz8a4F')// => Uint8Array [22, 225, 117, 19, 120, 60, 250, 61, 34, 48, 251, 162, 113, 208, 26, 211, 45, 233, 80, 7]
fromBytes

Convert 20 canonical KSUID bytes to a KSUID string.

fromBytes(bytes: Uint8Array): string
Exampleksuid.fromBytes(Uint8Array.from([22, 225, 117, 19, 120, 60, 250, 61, 34, 48, 251, 162, 113, 208, 26, 211, 45, 233, 80, 7]))// => '3GPXkrDipgmtLBpkbfrWSPz8a4F'
timestamp

Read the embedded Unix timestamp in milliseconds.

timestamp(id: string): number
Exampleksuid.timestamp('3GPXkrDipgmtLBpkbfrWSPz8a4F')// => 1783874323000
isValid

Return whether a value is a syntactically valid KSUID string.

isValid(id: unknown): id is string
Exampleksuid.isValid('3GPXkrDipgmtLBpkbfrWSPz8a4F')// => true
NIL

The nil KSUID (all zeros)

NIL: string
Exampleksuid.NIL// => '000000000000000000000000000'
MAX

The max KSUID (maximum valid value)

MAX: string
Exampleksuid.MAX// => 'aWgEPTl1tmebfsQzFP4bxwgy80V'