Skip to content

mofax/mksuid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

K-sortable unique id's with millisecond precision

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

Packages

 
 
 

Contributors