sparkid
v2.2.1
Published
Fast, time-sortable, 21-char Base58 unique ID generator
Maintainers
Readme
⚡ sparkid
Fast, monotonic, time-sortable, 21-char Base58 unique ID generator. Zero dependencies.
1ocmpHE1bFnygEBAPTzMK
1ocmpHE1bFnygFv4Wp4dL
1ocmpHE1bFnygGoUXUL7XInstall
npm install sparkidUsage
import { generateId } from "sparkid";
const id = generateId();
// => "1ocmpHE1bFnygEBAPTzMK"Extract timestamp
import { extractTimestamp } from "sparkid";
const id = generateId();
const date = extractTimestamp(id);
console.log(date.toISOString());
// => "2025-11-14T22:13:20.000Z"Binary representation
Pack IDs into 16 bytes for compact storage. Sort order is preserved — memcmp on the binary bytes gives the same ordering as string comparison.
import { toBytes, fromBytes } from "sparkid/binary";
const id = generateId();
const bytes = toBytes(id); // Uint8Array(16)
const restored = fromBytes(bytes);
console.log(id === restored); // trueProperties
| Property | Value |
|---|---|
| Length | 21 characters, fixed |
| Alphabet | Base58 (no 0, O, I, l) |
| Sortable | Lexicographically, by creation time |
| Monotonic | Strictly increasing within the process |
| URL-safe | Yes |
| Collision resistance | ~58^13 (~8.4 x 10^22) combinations per millisecond |
| Randomness | Cryptographically secure (crypto.getRandomValues) |
How it works
Each ID is composed of two parts:
[8-char timestamp][13-char suffix]- Timestamp (8 chars): Current time in milliseconds, Base58-encoded. IDs generated in a later millisecond always sort after earlier ones.
- Suffix (13 chars): Seeded from
crypto.getRandomValues(rejection-sampled, no modulo bias) at the start of each millisecond, then monotonically incremented for each subsequent ID within that millisecond. This guarantees strict ordering even when multiple IDs share a timestamp.
Ordering guarantees
All IDs generated by generateId() within a single process are strictly monotonically increasing — every ID is lexicographically greater than the one before it. Since JavaScript is single-threaded, this means process-wide monotonicity with no additional coordination needed.
Platform support
Works in any environment with crypto.getRandomValues:
- Node.js >= 19
- All modern browsers
- Deno
- Bun
- Cloudflare Workers
License
MIT
