npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

uuid-lab

v2.0.0

Published

Comprehensive ID generation library — UUID, NanoID, ULID, CUID2, Snowflake, and 280+ utilities

Readme

🚀 uuid-lab

The most advanced ID generation toolkit for Node.js & JavaScript
⚡ 200+ utilities · 🔐 Security-first · 🌍 Distributed-ready · 🧠 Smart · 📦 Production-grade

npm version license tests


Support & Queries

For any support requests, feature inquiries, or questions about enterprise capabilities, please email me at: [email protected]


Table of Contents


Installation

npm install uuid-lab

Quick Start

const uid = require('uuid-lab');

uid.nanoId();          // → 'V1StGXR8_Z5jdHi6B-myT'
uid.uuid();            // → 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
uid.ulid();            // → '01ARZ3NDEKTSV4RRFFQ69G5FAV'
uid.snowflakeId();     // → '7291234567890123'
uid.nanoId({ size: 12, alphabet: 'abc123' });

Core Generators

| Function | Description | Example Output | |---|---|---| | uuid() | UUID v4 | f47ac10b-58cc-4372-a567-... | | uuidV4() | UUID v4 explicit | f47ac10b-58cc-4372-a567-... | | uuidV7() | UUID v7 (time-ordered) | 018e2b5a-dead-7000-... | | uuidV5(name, ns) | UUID v5 (deterministic) | deterministic string | | nanoId(opts?) | Cryptographically secure random | V1StGXR8_Z5jdHi6B-myT | | ulid() | Sortable, URL-safe | 01ARZ3NDEKTSV4RRFFQ69G5FAV | | snowflakeId() | Twitter-style Snowflake | 7291234567890123 | | ksuid() | K-Sortable Unique ID | 27-char alphanumeric | | typedId(type) | Prefixed typed ID | usr_V1StGXR8_Z5jdHi6B | | humanId() | Human-readable words | brave-hawk-4521 | | sequentialId() | Auto-incrementing | 00000001 |


Format & Encoding

uid.prefixedId('usr');            // → 'usr_V1StGXR8_Z5jdHi6B-myT'
uid.shortId();                    // → 'aB3cD9'  (≤12 chars)
uid.customLengthId(32);           // → 32-char ID
uid.urlSafeId();                  // → no +/= chars
uid.base62Id();                   // → base62 chars only
uid.base36Id();                   // → lowercase alphanumeric
uid.visualId();                   // → easy-to-read font-safe
uid.emojiId();                    // → 🦊🌊🔥...
uid.compactId();                  // → shortest possible unique
uid.hashId('my-input');           // → deterministic SHA hash
uid.seededId('seed');             // → deterministic from seed
uid.encodeBase62(bigInt);         // encode number to base62
uid.decodeBase62(str);            // decode base62 to number

Security & Tokens

JWT-like Token IDs

const token = uid.tokenId({ userId: 42, role: 'admin' }, 'my-secret', {
  expiresIn: 3600   // seconds
});
// → 'eyJ...<signed payload>...'

const { valid, payload, expired } = uid.verifyTokenId(token, 'my-secret');
// → { valid: true, payload: { userId: 42, role: 'admin' }, expired: false }

Zero-Knowledge Commitments

// Commit to an ID without revealing it
const { commitment, blindingFactor } = uid.commitId('my-secret-id');

// Later, prove you know it without revealing the ID
const ok = uid.verifyCommitment(commitment, 'my-secret-id', blindingFactor);
// → true

Tamper-Proof IDs

uid.signId('my-id', 'secret');       // append HMAC signature
uid.encryptId('my-id', 'key');       // AES-256 encrypted
uid.expiringId({ ttl: 3600 });       // auto-expiring ID
uid.checkExpiry(id);                 // { expired: false, remainingMs: 3599000 }

Next-Gen Features (NEW)

uuid-lab now includes advanced identifier strategies that are rarely found in traditional libraries, pushing the boundaries of what an ID can do.

Holographic IDs (Error-Correcting)

Self-healing IDs that contain built-in redundancy. If a user mistypes a character, the library can mathematically repair the ID.

const id = uid.holographicId(); // → 'aB3cD9eF...CRC'
uid.verifyHolographic(id); // → true

// Simulate a typo: change 'a' to 'X'
const typo = 'X' + id.slice(1);
const result = uid.repairHolographic(typo); 
// → { valid: true, repaired: true, id: 'aB3cD9eF...' }

Steganographic IDs (Hidden Channel)

Embed 8-16 bits of secret metadata (like a version flag or role tag) directly inside a NanoID without altering its format or length.

const id = uid.steganoId(42, 'my-secret-key'); 
// → looks like a normal random NanoID

const hidden = uid.extractStegano(id, 'my-secret-key');
// → 42

Proof-of-Work IDs (Anti-Spam)

Decentralized rate-limiting for APIs. The client must perform computational work to generate a valid ID.

const { challenge, difficulty } = uid.generatePowChallenge({ difficulty: 4 });
const { id, hash } = uid.solvePowChallenge(challenge, difficulty);

uid.verifyPow(id, difficulty); // → true

Quantum-Lattice IDs

High-entropy IDs generated using an LWE (Learning With Errors) inspired mixing function to conceptualize quantum-resistant entropy generation.

const qid = uid.latticeId(); // → 'ql_8z3vP9mX...'

Bleeding-Edge Features (v10)

For the absolute bleeding-edge use cases, uuid-lab provides experimental algorithms that exist nowhere else in the Javascript ecosystem.

Fractal / Recursive IDs

Endlessly split IDs into sub-IDs completely offline.

const root = uid.fractalRoot('my-seed'); 
const child = uid.deriveFractalChild(root, 'child_1');
const grandchild = uid.deriveFractalChild(child, 'grandchild_1');

Hardware-Bound IDs

Cryptographically bind an ID to the specific machine's hardware signature (CPU model, RAM, MAC address).

const hwId = uid.hardwareId(); // → 'hw_a1b2c3d4_randomStr'
uid.verifyLocalHardware(hwId); // → true (if checked on the same machine)

ZKP (Zero-Knowledge) Linked IDs

Prove two random IDs were generated by the same identity without exposing the identity.

const identity = uid.createZkpIdentity();
const idA = uid.generateZkpId(identity);
const idB = uid.generateZkpId(identity);

// Prove idA and idB belong to the same entity
const proofToken = uid.createLinkProof(identity, idA, idB);

// Verifier checks it without knowing the private key
uid.verifyLinkProof(idA, idB, proofToken, identity.publicKey); // → true

AI-Adaptive Compressed IDs

A stateful generator that learns your naming patterns over time and automatically starts compressing frequent prefixes.

const adaptive = new uid.AdaptiveGenerator({ threshold: 5 });

// First 5 times: no compression
adaptive.generate('USER_GROUP_ABC'); // → 'USER_GROUP_ABC'
// ...

// After threshold is reached, it learns the prefix 'USER_GROUP_'
adaptive.generate('USER_GROUP_XYZ'); // → '~0XYZ'

adaptive.decompress('~0XYZ'); // → 'USER_GROUP_XYZ'

Parallel Generation (Worker Threads)

Generate millions of IDs using all CPU cores simultaneously:

const { generateParallel, terminateWorkers } = require('uuid-lab');

// Generate 1,000,000 nanoIds in parallel
const ids = await generateParallel('nanoId', 1_000_000);
console.log(ids.length);  // 1000000, ~160,000 IDs/sec

// Clean up when done
terminateWorkers();

Supported generators: nanoId, uuid, uuidV4, typedId, humanId, sequentialId, fromPattern


ID DSL & Templates

Define ID schemas with a simple pattern language:

const gen = uid.compileTemplate('ord-[date:YYYYMMDD]-[random:8]-[seq:4]');
gen();  // → 'ord-20260419-aB3cD9eF-0001'
gen();  // → 'ord-20260419-xY7pQ2rS-0002'

Available tokens:

| Token | Description | Example | |---|---|---| | [random:N] | N random URL-safe chars | aB3cD9eF | | [date:FORMAT] | Date using YYYY/MM/DD | 20260419 | | [uuid] | Full UUID v4 | f47ac10b-... | | [nano] | NanoID (21 chars) | V1StGXR8_Z5jd... | | [ulid] | ULID (26 chars) | 01ARZ3NDEK... | | [seq:N] | Zero-padded sequence | 0042 | | [ts] | Unix timestamp ms | 1713526800000 | | [literal] | Literal text | as-is |


Smart Recommendation

Let the library choose the best generator for your requirements:

const results = uid.recommendId(['sortable', 'urlSafe', 'distributed']);

// → [
//   { type: 'ulid', matchPercentage: 100, description: '...' },
//   { type: 'uuidV7', matchPercentage: 75, description: '...' },
//   ...
// ]

Available requirement tags: sortable, urlSafe, distributed, secure, humanReadable, short, deterministic, collision-resistant


Distributed Systems

Multi-Service ID Federation

const { FederationNode, createFederation } = require('uuid-lab');

const node = new FederationNode({ nodeId: 'eu-west-1', strategy: 'snowflake' });
const id = node.generate();          // unique per node, globally unique

const fed = createFederation();
fed.join(node);
const { owner } = fed.verify(id);   // → 'eu-west-1'

Clock Drift Handling

Snowflake generation is now protected against NTP clock drift:

const node = new FederationNode({
  nodeId: 'node-1',
  strategy: 'snowflake',
  clockDriftStrategy: 'logical'  // or 'reject'
});

ID Reservation System

Safely reserve IDs before committing them (prevents race conditions):

const detector = uid.createDetector();
const reservation = await detector.reserve('my-id');

// ... validate your data ...

await detector.commitReservation(reservation.token);   // lock it in
// or
await detector.releaseReservation(reservation.token);  // roll back

Multi-Region Topology IDs

uid.topoId({ country: 'DE', dc: 'eu-central-1' });
// → 'DE_ec1_20260419_V1StGXR8'

const meta = uid.parseTopology(id);
// → { country: 'DE', dc: 'eu-central-1', isEU: true, date: '2026-04-19' }

Collision Detection

const detector = uid.createDetector({ namespace: 'users' });

const result = await detector.checkAndRegister('some-id');
// → { registered: true, isCollision: false }

const result2 = await detector.checkAndRegister('some-id');
// → { registered: false, isCollision: true }

detector.stats();
// → { registrations: 2, collisions: 1, collisionRate: 0.5, bloomFillRatio: 0.001 }

Redis backend:

const detector = uid.createDetector({
  namespace: 'prod',
  backend: 'redis',
  redisUrl: 'redis://localhost:6379'
});

Namespace System

uid.defineNamespace('payments', { prefix: 'pay', separator: '_' });

const id = uid.namespaceId('payments');  // → 'pay_V1StGXR8_Z5jdHi6B'
uid.belongsTo(id, 'payments');           // → true
uid.detectNamespace(id);                 // → 'payments'
uid.listNamespaces();                    // → ['payments', ...]

// Environment-aware IDs
uid.setEnvironment('prod');
uid.envId('payments');                   // → 'prod_pay_V1StGXR8...'

Hierarchical IDs

const org  = uid.hierarchyRoot({ label: 'org' });
const team = uid.hierarchyChild(org, { label: 'team' });
const user = uid.hierarchyChild(team, { label: 'user' });

uid.depthOf(user);              // → 2
uid.parentOf(user);             // → team id
uid.isDescendant(user, org);    // → true
uid.isDirectChild(team, org);   // → true
uid.parseHierarchy(user);       // → { depth: 2, root, parent, leaf, labels }

// Subtree range queries (for range-based DB scans)
uid.subtreeRange(team);         // → { gte: '...', lte: '...' }

// Lowest Common Ancestor
uid.lca(user1, user2);          // → team id

// Topological sort
uid.topoSort([user, team, org]); // → [org, team, user]

Compound & Fuzzy IDs

Compound IDs

const id = uid.compoundId([userId, orderId]);
const { valid, components } = uid.splitId(id);
// → { valid: true, components: [userId, orderId] }

uid.hasComponent(id, userId);            // → true
uid.sharedComponents(id1, id2);         // → common component IDs
uid.timedCompoundId([a, b]);            // → compound + timestamp

Fuzzy / Typo-Resistant IDs

const id = uid.fuzzyId({ prefix: 'INV' });
// uses Crockford Base32 (no confusing chars: O/0, I/l)

const { valid, autoFixed } = uid.validateFuzzy(id);
const corrected = uid.correctFuzzy(typoId);  // auto-correct common typos
uid.parseFuzzy(id);  // → { body, checkChar, valid, prefix }

Lifecycle & State IDs

const id = uid.lifecycleId('order', 'pending');
uid.verifyState(id, 'pending');           // → true
uid.verifyState(id, 'shipped');           // → false

const updated = uid.transitionState(id, 'shipped', {
  allowed: ['pending → processing', 'processing → shipped']
});

// Full lifecycle history
uid.getHistory(id);      // → [{ from, to, ts, reason }, ...]
uid.replayHistory(id);   // → { valid, states, steps }
uid.getTimeline(id);     // → [{ state, enteredAt, duration, isCurrent }]

Semantic & Relationship IDs

// Semantic IDs embed type/role/region
const id = uid.semanticId({ type: 'user', role: 'admin', region: 'eu' });
uid.validateSemantic(id);          // → { valid: true }
uid.parseSemantic(id);             // → { type: 'user', role: 'admin', region: 'eu' }

// Relationship-encoded IDs
const child = uid.linkedId(parentId, childIndex, 'secret');
uid.verifyLink(child, parentId, 'secret');   // → true

// Role-scoped IDs (same entity, different per role)
const adminView  = uid.scopedId('user-123', 'admin');
const guestView  = uid.scopedId('user-123', 'guest');
// adminView !== guestView, but both map back to 'user-123'

Time-based IDs

uid.timestampId();                        // → ID with embedded timestamp
uid.extractTime(ulid);                    // → Date object
uid.timeWindowId({ window: 60_000 });     // same per 60s window
uid.epochDayId();                         // same for the whole day
uid.contextId('checkout');                // → 'checkout_<timestamp>_<random>'
uid.meaningfulId();                       // → 'swift-hawk_<timestamp>'
uid.pronounceableId();                    // → easy to say aloud
uid.multiFormatId('my-id', ['hex', 'base64']); // multiple encodings at once

Analytics & Observability

Metrics API

const snap = uid.dashboardSnapshot();
// → {
//     capturedAt, uptimeHuman,
//     generation: { total, byType: { nanoId: 42, ... } },
//     latency: { p50, p95, p99, min, max, mean },
//     collisions: { total, byNamespace },
//     federation: { nodes, totalGenerated },
//     alerts: []
//   }

uid.renderAsciiDashboard();  // pretty terminal dashboard

Event Hooks

uid.on('generate', ({ type, id }) => console.log('Generated:', type, id));
uid.on('collision', ({ id, namespace }) => alert(`Collision: ${id}`));
uid.once('generate', handler);   // fire once
uid.off('generate', handler);    // unsubscribe

Logging / Debug

uid.enableDebug();
uid.debugWrap('myGen', () => uid.nanoId());
uid.getDebugLog();    // → [{ label, id, durationMs, ts }]
uid.clearDebugLog();
uid.disableDebug();

Telemetry

const report = uid.flushTelemetry();
// → { generated, collisions, peakRate, uptime, latencyPercentiles, histogram }

GDPR / HIPAA Compliance

// Scan an ID for accidentally embedded PII
uid.scanForPII('[email protected]_abc123');
// → { risk: 'high', findings: [{ type: 'email', risk: 'high' }] }

// Verify pseudonymization
uid.verifyPseudonymization(id);
// → { verdict: 'COMPLIANT', checks: [...], gdprArticle: 'Art. 4(5)' }

// Data residency check
uid.checkDataResidency(topoId);
// → { compliant: true, region: 'EU', gdprApplies: true }

// Full compliance report
const report = uid.generateComplianceReport([id1, id2, id3]);
uid.formatReport(report);  // → formatted string report

Ecosystem Integrations

Express Middleware

const express = require('express');
const { expressMiddleware } = require('uuid-lab');

const app = express();
app.use(expressMiddleware({ headerName: 'X-Request-Id' }));
// req.id and res header are now automatically set on every request

Mongoose Plugin

const mongoose = require('mongoose');
const { mongoosePlugin } = require('uuid-lab');

const UserSchema = new mongoose.Schema({ name: String });
UserSchema.plugin(mongoosePlugin, { field: '_id', generator: () => uid.nanoId() });

Sequelize Adapter

const { DataTypes } = require('sequelize');
const { sequelizeAdapter } = require('uuid-lab');

const User = sequelize.define('User', {
  id: sequelizeAdapter(DataTypes.STRING, { generator: () => uid.nanoId() })
});

GraphQL Custom Scalar

const { GraphQLScalarType } = require('graphql');
const { createGraphQLScalar } = require('uuid-lab');

const NanoIdScalar = new GraphQLScalarType(
  createGraphQLScalar('NanoID', (val) => val.length === 21)
);

Framework Support

React (SSR-safe)

const { createReactHooks } = require('uuid-lab');
const { useSafeId, useCorrelationId } = createReactHooks(React);

function MyComponent() {
  const id = useSafeId('btn-');     // hydration-safe unique ID
  return <button id={id}>Click</button>;
}

Vue 3 Composables

const { createVueComposables } = require('uuid-lab');
const { useSafeId } = createVueComposables(vue);

// In your setup():
const id = useSafeId('input-');  // reactive ref, updates after mount

Next.js / SSR

const { ssrSafeId } = require('uuid-lab');

// Returns a deterministic prefix-based ID on the server,
// and a random ID on the client — preventing hydration mismatches
const id = ssrSafeId('ssr');

ID Migration & Versioning

// Detect format of any legacy ID
uid.detectFormat('f47ac10b-58cc-4372-a567-0e02b2c3d479');  // → 'uuid-v4'
uid.detectFormat('01ARZ3NDEKTSV4RRFFQ69G5FAV');            // → 'ulid'
uid.detectFormat('12345');                                  // → 'legacy-int'

// Migrate old IDs to new format
const { newId, oldId, isMigrated } = uid.migrateId(legacyId);
uid.isMigrated(newId);              // → true
uid.recoverOriginal(newId);         // → { originalId, version, integrity: true }

// Batch migrate
const results = uid.batchMigrate([id1, id2, id3]);

// Migration audit log
uid.getMigrationLog();              // → [{ from, to, reason, ts }]
uid.clearMigrationLog();

DevTools & CLI

Interactive CLI

# Generate IDs
npx uuid-lab generate nanoid
npx uuid-lab generate uuid --count 5
npx uuid-lab generate nanoId --count 10 --size 12

# Decode any ID
npx uuid-lab decode f47ac10b-58cc-4372-a567-0e02b2c3d479

# Help
npx uuid-lab help

Error Handling

const { createError, ErrorCodes } = require('uuid-lab');

throw createError('ID already exists', ErrorCodes.COLLISION, { id: 'my-id' });
// → UuidLabError: ID already exists [COLLISION] { id: 'my-id' }

Validation

uid.validate('some-id', { minLength: 8, noSpaces: true });
// → { valid: true, violations: [] }

uid.validateBatch([id1, id2, id3], rules);
// → { total: 3, invalid: 1, results: [...] }

uid.commonRules.noEmpty(id);
uid.commonRules.minLength(8)(id);

Code Generation

uid.generateSchemaDocs(schema);   // → markdown table
uid.generateTypeScript(schema);   // → TypeScript interface
uid.generateDocs(schema);         // → full docs page

Testing Utilities

uid.withMock(() => uid.nanoId(), 'mock-id-123');  // returns mock during fn
uid.testIds(5, 'nanoid');         // → deterministic test IDs
uid.assertId(id, { type: 'nanoid', length: 21 });

High-Performance Pool

Pre-generates IDs in background batches for zero-latency retrieval:

const pool = uid.createHighPerfPool(uid.nanoId, {
  size: 1000,
  refillThreshold: 0.2   // refill when 20% remaining
});

pool.get();             // instant, pre-generated
pool.drain(50);         // pull 50 IDs at once
pool.peek();            // preview without consuming
pool.stats();           // { poolSize, generated, hits, refills, hitRate }
pool.size;              // current available count

The pool auto-scales — it increases batch size when hit rate is high and decreases it when utilization is low.


Blockchain-style ID Chain

Tamper-evident, cryptographically-linked audit trails:

const chain = uid.createChain({ hashAlgorithm: 'sha256' });  // or 'sha512'

const genesis = chain.genesis({ data: 'audit-start' });
const block1  = chain.add(uid.nanoId(), { label: 'user-created' });
const block2  = chain.add(uid.nanoId(), { label: 'order-placed' });

chain.verify();          // → true (tamper-proof)
chain.length;            // → 3
chain.getLast();         // → block2
chain.find(genesis.id);  // → genesis block
chain.toJSON();          // → { valid: true, length: 3, blocks: [...] }

QR Code Generation

// ASCII art QR (terminal display)
const ascii = uid.idToQrAscii('my-id');
console.log(ascii);

// Data URL (embed in HTML/PDF)
const dataUrl = uid.idToQrDataUrl('my-id');
// → 'data:text/plain;base64,...'

TypeScript Support

Full TypeScript definitions included — no @types package needed.

import {
  nanoId, uuid, ulid,
  generateParallel,
  tokenId, verifyTokenId, commitId, verifyCommitment,
  compileTemplate, recommendId,
  expressMiddleware, mongoosePlugin, sequelizeAdapter, createGraphQLScalar,
  ssrSafeId, createReactHooks, createVueComposables,
  createChain, IdChain, idToQrAscii,
  createHighPerfPool, HighPerformancePool,
} from 'uuid-lab';

const ids: string[] = await generateParallel('nanoId', 10000);
const gen: () => string = compileTemplate('order-[date:YYYYMMDD]-[random:8]');

ESM Support

// Works natively with ES Modules
import { nanoId, generateParallel, tokenId, compileTemplate } from 'uuid-lab';

Testing

Run the full test suite:

node test-v3.js   # Semantic, Relationship, Entropy, Topology — 122 tests
node test-v4.js   # Fuzzy, Compound, Hierarchy, Migration — 142 tests
node test-v5.js   # Collision Detection, Federation, GDPR — 124 tests
node test-v6.js   # Decode, Batch Verify, Query, DevTools — 147 tests
node test-v7.js   # Format, Namespace, Time-based, Analytics — 129 tests
node test-v8.js   # Chain, QR, Pool, Integration — 74 tests
node test-nextgen.js # Holographic, Steganographic, PoW, Lattice — 20 tests
node test-bleeding-edge.js # Fractal, Hardware, ZKP, Adaptive — 18 tests

node verify.js       # Verify all 16 new features load correctly
node test-fuzz.js    # Fuzz test: 10,000 garbage inputs
node test-stress.js  # Stress test: 1,000,000 IDs via worker threads

Total: 776 tests, 0 failures

| Metric | Result | |---|---| | Tests passing | ✅ 776 / 776 | | Fuzz safety | ✅ 10,000 random inputs handled | | Throughput | ⚡ ~160,000+ IDs/sec (parallel) | | Collisions (1M sample) | ✅ 0 detected |


License

MIT © Mayur Patel