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
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(): stringGenerate 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): TBufGenerate a KSUID string with optional timestamp or random payload bytes.
ksuid(options?: KsuidOptions, buf?: undefined, offset?: number): stringExampleksuid()// => '3GPXkrDipgmtLBpkbfrWSPz8a4F'- toBytes
Convert a KSUID string to its canonical 20-byte representation.
toBytes(id: string): Uint8ArrayExampleksuid.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): stringExampleksuid.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): numberExampleksuid.timestamp('3GPXkrDipgmtLBpkbfrWSPz8a4F')// => 1783874323000- isValid
Return whether a value is a syntactically valid KSUID string.
isValid(id: unknown): id is stringExampleksuid.isValid('3GPXkrDipgmtLBpkbfrWSPz8a4F')// => true- NIL
The nil KSUID (all zeros)
NIL: stringExampleksuid.NIL// => '000000000000000000000000000'- MAX
The max KSUID (maximum valid value)
MAX: stringExampleksuid.MAX// => 'aWgEPTl1tmebfsQzFP4bxwgy80V'