ID generation for JavaScript & TypeScript applications.
Example Usage:
import { IdRandom, IdDeterministic, IdSortable, utils } from '@matrixai/id';
// Random ids, equivalent to UUIDv4
const randGen = new IdRandom();
const randIds = [...utils.take(randGen, 3)];
console.log(randIds.map((b) => utils.toUUID(b)));
// Deterministic ids, using the SHA-256 UUIDv8 profile
const deteGen = new IdDeterministic({
namespace: 'foo',
});
const deteId1 = deteGen.get();
const deteId2 = deteGen.get('bar');
const deteId3 = deteGen.get('bar');
console.log(utils.toUUID(deteId1));
console.log(utils.toMultibase(deteId2, 'base32hex'));
// Will be cast to string index
const recordOfDeteIds = {};
recordOfDeteIds[deteId1] = 1;
recordOfDeteIds[deteId2] = 1;
console.log(recordOfDeteIds[deteId1]);
// Can be checked for equality
console.log(deteId2.equals(deteId3));
// Binary string form can be checked for equality
console.log(deteId2.toString() === deteId3.toString());
// Per-generator monotonic sortable ids using RFC 9562 UUIDv7
const sortGen = new IdSortable();
const sortId1 = sortGen.get();
const sortId2 = sortGen.get();
const sortId3 = sortGen.get();
const sortIds = [
utils.toBuffer(sortId2),
utils.toBuffer(sortId3),
utils.toBuffer(sortId1),
];
sortIds.sort(Buffer.compare);
console.log(sortIds);
// Save and restore the latest ID under exclusive generator ownership
const lastId = sortGen.lastId;
const resumedGen = new IdSortable({ lastId });
console.log(lastId < resumedGen.get());
// Ids can also be compared in order
console.log(sortId1 < sortId2);
console.log(sortId2 < sortId3);An ID is a mutable byte-array value, not a JavaScript number. Its primitive
coercion produces a binary string whose code units preserve byte order. The
TypeScript intersection with number is a type-system workaround that permits
object-key indexing; it does not make arithmetic meaningful. Object keys use
that string representation, while Map keys use object identity. Mutating bytes
can change the key produced by later coercion. Buffer conversion shares storage.
Subclass factories and decoders construct the invoked subclass. Generator type
parameters support compile-time branding but do not select a runtime subclass;
generators construct IdInternal values. To obtain subclass behavior, construct
the subclass explicitly from generated bytes:
import { IdInternal, IdSortable } from '@matrixai/id';
class NodeIdInternal extends IdInternal {}
const nodeId = NodeIdInternal.create(new IdSortable().get());Passing an ID to this factory copies its bytes. A buffer passed with an offset and length instead creates a shared view.
The deterministic generator uses the RFC 9562 Appendix B.2 SHA-256 UUIDv8 construction: hash 16 namespace bytes followed by the UTF-8 name, take the first 16 digest bytes, and set the UUIDv8 version and RFC variant bits. Supply a 16-byte namespace to interoperate with another implementation of this profile:
const namespace = utils.fromUUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8');
const dnsIds = new IdDeterministic({ namespace: namespace! });
console.log(dnsIds.get('www.example.com').toUUID());
// 5c146b14-3c52-8afd-938a-375d0df1fbf6For a string namespace, the generator first derives its 16 namespace bytes with the same profile, using the nil UUID as the namespace and the supplied string as the name. The default namespace is the empty string. Input strings use standard UTF-8 conversion without Unicode normalization; unpaired UTF-16 surrogates are replaced by the Unicode replacement character. The generator copies supplied namespace bytes. Other UUIDv8 identifiers do not necessarily use this profile.
This is a breaking change from the earlier SHA-1 UUIDv5 generator: the same namespace and name now produce different bytes. These identifiers are not credentials or password hashes, and low-entropy names are guessable. Truncation and UUID markers leave 122 hash-derived bits, not the full SHA-256 digest.
The sortable generator encodes Unix milliseconds in the first 48 bits. It uses a
randomly seeded 12-bit counter with a leading guard bit and 62 random bits. When
the clock stalls or moves backwards, it retains the previous timestamp and
increments the counter. If the counter is exhausted, it throws a RangeError
rather than wrapping. Generation may resume after the clock advances.
Ordering is guaranteed within one generator, not globally across independent generators or machines. Restart ordering requires the caller to retain the last issued ID durably, prevent concurrent owners from using the same state, and restore a UUID generated by this profile. The generator copies its saved state; mutating a returned ID does not alter that state. A restored ID's version bits cannot distinguish this profile from older nonstandard sortable values, which are not supported by the new generator. Do not mix them as restart state or rely on their combined chronological ordering. Embedded node IDs are not part of the UUIDv7 generator.
Both sortable generators expose tryGet(): it returns a new ID, or undefined
only when the sequence is exhausted at the held timestamp. An invalid clock,
invalid random result, or exception from a collaborator still throws. The
existing get() and iterator methods continue to throw RangeError on
exhaustion. Neither failure advances committed generator state.
Applications that need to retry can apply backpressure and retain the same generator. For example, a service may supply its own cancellable, delayed wait:
import { IdSortable } from '@matrixai/id';
async function issueWithBackpressure(
generator: IdSortable,
waitForRetry: (signal: AbortSignal) => Promise<void>,
signal: AbortSignal,
) {
for (;;) {
signal.throwIfAborted();
const id = generator.tryGet();
if (id !== undefined) return id;
await waitForRetry(signal);
}
}The application must supply a wait that yields, delays repeated attempts, and
honors cancellation, as well as a request deadline or other bound. A timer
firing does not ensure that the generator's clock advanced: a stalled or
rolled-back clock may require many retries or never recover. Bound the queue and
propagate timeout or cancellation rather than busy-looping or waiting
indefinitely. Do not catch every RangeError as exhaustion, inspect
error-message text, reset the generator, or switch profiles to evade the limit.
The same pattern applies to IdFlake.
For UUIDv7, a fresh millisecond has 2,049 to 4,096 available values, depending on its random counter seed; restored state may have fewer. A flake's configured sequence width provides up to 2^sequenceBits values per fresh timestamp. A wider sequence consumes bits otherwise available for the node prefix or random tail; it does not solve clock stalls indefinitely or replace coordination and durable state ownership. Independent generators do not provide one global order.
IdFlake generates a separate, configurable UUIDv8 profile. It stores a 48-bit
Unix millisecond timestamp, the version and variant bits, and a 74-bit payload.
The payload contains the sequence, leading node bits, and random tail, in that
order. UUIDv8 reserves the version and variant, but does not standardize these
profile fields or identify the allocation in the value.
import { IdFlake, idFlake } from '@matrixai/id';
const nodeId = Uint8Array.of(0x12, 0x34, 0x56, 0x78);
const generator = new IdFlake({ nodeId, sequenceBits: 42, nodeBits: 32 });
const id = generator.get();
console.log(id.toUUID(), idFlake.extractSeq(id, 42));
console.log(idFlake.extractNodeId(id, { sequenceBits: 42, nodeBits: 32 }));The sequence width defaults to 12 bits and can be set from 1 through 74. The node width defaults to the supplied node byte length capped at 62 bits; callers can explicitly select a different width that fits the remaining budget and the supplied bytes. Longer node inputs are truncated to their leading selected bits: they are not hashed, allocated, or guaranteed unique. For example, a 12-bit sequence with 62 node bits leaves no random tail; 42 sequence bits and 32 node bits also leave none; 12 sequence bits and 32 node bits leave 30 random bits. The default with no node uses 62 random bits. Non-byte-aligned prefixes use the most significant bits and extraction returns zero-padded, left-aligned bytes.
Sequence values start at zero on a new timestamp, increment when time stalls or
rolls back, and throw RangeError before overflow. Failed random sources leave
generator state unchanged. The random source is not called when the random tail
is empty. Sequence extraction returns bigint so widths above 53 bits remain
exact. The last-generated accessor returns a copy and is unavailable until this
instance generates an ID, even if restart state was supplied.
Consumers of a shared ID space must agree on the allocation, including field widths and node prefix, and prevent overlapping node assignments. Different prefix lengths can overlap, and UUIDv8 bits alone cannot distinguish layouts or the separate name-based UUIDv8 profile. Restart validation checks version, variant, and the configured node bits but cannot prove profile provenance. Allocate exclusive ownership and persist or reserve state before exposing IDs when crash-safe uniqueness is required; the generator does neither for the caller. Timestamps and node bits are exposed, IDs are not secrets, and different generators do not establish global creation order.
Base Encoding and Lexicographic Order
It is important to realise that not all base-encodings preserve lexicographic
sort order. The UUID (hex-encoding) and base32hex does, but base58btc and
base64 does not. Make sure to pick an appropriate base encoding if you are
expecting to compare the IdSortable as base-encoded strings.
Out of all the multibase encodings, the only ones that preserve sort order are:
base2
base8
base16
base16upper
base32hex
base32hexupper
base32hexpad
base32hexpadupper
In addition to this, JS binary string encoding through id.toString() also
preserves sort order.
For an ordered byte-key database, store the identifier bytes directly and verify the database comparator and any composite-key framing. With an unsigned bytewise comparator, UUIDv7's big-endian timestamp gives time-oriented key locality; it does not guarantee global issuance order across generators. A binary string is not a raw-byte transport: passing it through UTF-8 changes bytes above 127. The Node buffer view shares the ID's storage, so do not mutate either while a consumer depends on its contents.
The unpadded sortable base64 codec uses the ASCII-ordered alphabet
-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz. It encodes
16 bytes in 22 characters. For equal-length inputs, its text order matches
unsigned byte order when compared using binary ASCII collation. The alphabet
matches the individual
Base64sort Internet-Draft,
which expired in October 2026 and is not an RFC. The default encoder is
unpadded; the separate padded encoder accepts = or ~ as its second argument.
The decoder accepts both padded forms and unpadded text, rejecting mixed or
misplaced padding, noncanonical lengths, characters, and unused trailing bits.
It has no assigned prefix in the
multibase registry.
The separately registered base32hex is another sortable option for equal-length
inputs under binary collation, but is longer and is marked experimental in that
registry.
import { IdSortable, utils } from '@matrixai/id';
const id = new IdSortable().get();
const compact = utils.toSortableBase64(id);
const decoded = utils.fromSortableBase64(compact);
const padded = utils.toSortableBase64Padded(id, '=');TypeID 0.3 uses a 26-character UUID suffix and an optional semantic prefix. The
codec accepts any supplied 16-byte UUID value, including UUIDs of versions other
than v7; it does not generate IDs. Generate a new UUIDv7 first when producing a
new TypeID. Decoding returns both the prefix and copied identifier bytes, or
undefined for invalid text. Applications own prefix allocation and validation
against their expected domain. A prefix does not authenticate the identifier.
const typed = utils.toTypeId(id, 'user');
const parsed = utils.fromTypeId(typed);
if (parsed?.prefix === 'user') {
console.log(parsed.id.toUUID());
}TypeID's prefix is not a multibase prefix, and its base32 suffix differs from the sortable base64 format. Text comparison across differing prefixes orders the prefixes first, not UUID timestamps. Neither representation is a secret.
The multibase functions encode and decode bytes with supported multibase codecs;
they do not parse or validate the bytes as a CID, multihash, or other structure.
For example, a supported multibase-encoded CIDv1 string can be decoded to its
bytes and passed to the CID APIs in multiformats. A CIDv1 is more than its
encoding: it contains a version, content-type multicodec, and multihash. The
usual CIDv0 text is an unprefixed base58btc special case and is not accepted by
the multibase decoder as such. UUIDs, including the SHA-256 UUIDv8 profile, are
not automatically CIDs or multihashes. CID construction and verification, IPLD
codecs, IPFS retrieval, and networking are outside this library's contract; use
the relevant ecosystem libraries. See the
CID specification.
This major version changes identifier generation contracts and is not a compatible update to the previous major version:
- Old sortable values and RFC UUIDv7 values share version bits but encode their timestamps differently. Do not infer their origin from those bits, mix them in chronological indexes, or restore old generator state into the new generator.
- The deterministic generator changes from SHA-1 UUIDv5 to SHA-256 UUIDv8. The same names and namespaces produce different IDs; stored references and wire contracts need an explicit application-owned adoption decision.
- The sortable generator no longer accepts embedded node bytes. Use UUIDv7 for general sortable generation, or select node bytes and bit widths on the separate UUIDv8 flake profile. Its timestamp and version differ from the old generator; the application owns node allocation and crash-safe state.
- UUID parsing now rejects malformed text. Applications must not rely on the previous permissive decoding of invalid input.
Inventory database keys, sort ranges, cursors, persisted restart state, and external references before adopting the new major version. No old-layout reader, automatic detection, or data migration is supplied. Database and production changes require their own reviewed plan.
One local Node 24.21.0 run on Linux x86-64 measured the median of eight samples, each generating 100,000 identifiers after a warmup. The synthetic clock advanced once per 1,024 IDs. These are whole-batch times, not latency for a single ID:
| Scenario | Candidate median | Adapted old sortable median |
|---|---|---|
| Sortable UUIDv7, zero-filled random source | 78.8 ms | 184.6 ms |
| Sortable UUIDv7, Web Crypto | 133.2 ms | 307.6 ms |
| Name-based SHA-256 UUIDv8 | 236.9 ms | not measured |
| Flake, 12 sequence and 62 node bits, no random tail | 19.6 ms | not measured |
| Flake, 42 sequence and 32 node bits, no random tail | 25.0 ms | not measured |
| Flake, 12 sequence and 32 node bits, Web Crypto tail | 151.0 ms | not measured |
For example, 133.2 ms per 100,000 IDs corresponds to about 750,000 IDs per second as a batch average in this run. It is not an individual latency distribution or a sustained-rate guarantee. The candidate batch medians were about 2.3 times faster than the adapted old sortable source in each comparison, but the implementations have different layouts, random-byte counts, state ownership, and shared helpers. The baseline is not a full historical build. The no-random-tail flake profiles require coordinated node and state ownership; their timings are not equivalent to generation with a cryptographic random tail.
The run used an uncontrolled Intel Core i9-13900KF, with no CPU isolation or
frequency policy. Its candidate bundle SHA-256 was
d1c9ffdfd0db3e9ba86704a056822abbcd0952fd6f5ee57513c6f61b4c0dd2b1; the adapted
baseline source revision is recorded in the
baseline provider. The
retained observation includes the
individual samples and provenance. These are exploratory microbenchmarks, not
correctness evidence, a performance budget, a regression gate, or a database,
browser, or deployed Worker measurement. See the
performance evidence guide to reproduce and interpret them.
npm install --save @matrixai/idNode.js 24 or newer is required. Enter the integrated environment with
nix develop, or review and allow .envrc for automatic direnv
activation. Activation does not load credentials, install dependencies, or
change persistent shell options. Install project dependencies explicitly:
npm ci --ignore-scripts
npm run build
npm testVitest compiles the package incrementally first and imports built modules
through the package mapping. A matching build may be supplied with
npm test -- --prebuilt. JUnit results are written under
tmp/junit, and optional coverage results under
tmp/coverage.
MatrixAI lint comes from the selected nixpkgs-matrixai package set, not an npm dependency or a separate lint flake input. One configured tool environment is shared by the development shell, hermetic lint check, and Nix formatter. The repository's TypeScript compiler remains a project dependency.
nix fmt
npm run lintfix
npm run lintThe first two commands run the same formatting authority across applicable domains, including TypeScript, Markdown, shell, and Nix. The last command is nonmutating verification. No global npm lint installation is required.
The manifest allowlists emitted code and declarations, excluding development artifacts and compiler cache metadata. The tests exercise identifier compatibility vectors through the compiled package.
The default Nix check aggregates unit tests, typechecking, and the shared lint check. Both checks run independently of an activated development shell:
nix flake check
nix build '.#npm-package'The separate browser integration check runs the compiled library in a Chromium document and dedicated worker without a server or Buffer polyfill:
nix build '.#checks.x86_64-linux.integration-browser'The package output is a prepared npm archive, with a separate unpacked output and dependency metadata for downstream Nix consumption. It preserves the canonical manifest and does not substitute unpublished sibling checkouts.
The shared runtime uses Web Crypto for random bytes and the platform performance clock. Node.js and the hermetic Chromium document and dedicated-worker cases are tested. Buffer conversions are Node-specific and expose shared storage; browser consumers can use the underlying byte array directly. This browser check is not evidence of deployed Cloudflare Workers or other browsers.
In deployed Cloudflare Workers, platform clocks may advance only after I/O. A generator can exhaust its per-timestamp counter while the clock is frozen and will throw rather than silently reuse a counter. See the Cloudflare timer documentation.
Start from repository guidance, the profile selector, and the pinned private standards submodule. Materialized skills are derived from that checkout's profile and ecosystem collections. Private acquisition failures are blockers, not permission to bypass checks.
Documentation is handwritten Markdown; generated API documentation is not maintained. Accepted identifier contracts are recorded in specs. Unit and hermetic checks provide the executable validation gates.
There is no automatic npm publication workflow. A Git tag alone does not publish the package. Family integration uses released dependencies with exact lockfile resolutions. Committing, tagging, and publishing require separate approval.