npm.io
0.3.2 • Published 2 months ago

mksuid

Licence
MIT
Version
0.3.2
Deps
0
Size
10 kB
Vulns
0
Weekly
0
Stars
5

mksuid

Millisecond-precision, time-prefixed unique IDs inspired by KSUID.

mksuid generates a base62-encoded ID that embeds the creation time and a random payload.

Install

npm install mksuid

Usage

import mksuid, { parse } from "mksuid";

const id = mksuid();
// => base62 string

const decoded = parse(id);
// => {
//      time: Date,
//      payload: Uint8Array
//    }

You can also generate an ID for a specific date:

import mksuid, { parse } from "mksuid";

const date = new Date("2026-04-05T12:34:56.789Z");
const id = mksuid(date);
const decoded = parse(id);

console.log(decoded.time.toISOString());
// 2026-04-05T12:34:56.789Z

API

mksuid(date?: Date): string

Generates a new ID.

  • If date is omitted, the current time is used.
  • Randomness comes from crypto.getRandomValues.
parse(id: string): { time: Date; payload: Uint8Array }

Decodes an ID generated by mksuid.

Returns:

  • time: the embedded timestamp as a Date
  • payload: the random payload as a Uint8Array

Throws if the input is not a valid mksuid string.

Format

An mksuid value encodes:

  • 1 byte: timestamp length marker
  • 6 bytes: timestamp in milliseconds since the Unix epoch
  • 14 bytes: random payload

The full 21-byte value is then base62-encoded.

Runtime notes

This package expects a modern JavaScript runtime with:

  • crypto.getRandomValues
  • Buffer

That includes Bun and modern versions of Node.js.

Development

bun install
bun test
bun run build

License

MIT