uuidv7

A lightweight, RFC 9562-compliant JavaScript/TypeScript library for generating monotonic, timestamp-sortable UUIDv7 identifiers (with UUIDv4 support too).

Library
npm
v1.2.1
270stars
Apache License 2.0

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
48/100Fair
Development Activity60
Maintenance20
Community36
Maturity56
Momentum20

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
77/100Good
Architecture82
Code Quality78
Innovation68
Learning Curve80

uuidv7 is a small, dependency-free JavaScript implementation of UUID version 7 as defined in RFC 9562. Unlike random UUIDv4 values, UUIDv7 embeds a millisecond-precision Unix timestamp in the leading bits, so identifiers generated in sequence sort lexicographically in the same order they were created — a property that matters for database primary keys, event logs, and any system that benefits from time-ordered, index-friendly IDs.

The library exposes both simple string-returning functions (uuidv7(), uuidv4()) and object-oriented equivalents (uuidv7obj(), uuidv4obj()) that return a UUID class instance with toString(), toHex(), compareTo(), equals(), and variant/version introspection methods. For applications that need an isolated counter state — for example, per-request or per-worker generation — the V7Generator class can be instantiated directly, and it offers a generateOrAbort() variant that returns undefined instead of silently breaking monotonic ordering when the system clock rolls back significantly.

A uuidv7 CLI is bundled via npx uuidv7, letting you generate one or many IDs from the command line without writing any code. The library targets both Node.js and browser/Deno environments, using the Web Crypto API for cryptographically strong randomness where available and falling back to Math.random() otherwise (with an opt-in flag to reject the weak fallback).

What You Get

  • uuidv7() / uuidv7obj() - one-line generation of a UUIDv7 as a string or as a structured UUID object with introspection methods.
  • V7Generator class - an isolated, stateful generator with configurable clock-rollback tolerance (rollbackAllowance) and both a safe (generate) and strict (generateOrAbort) generation mode.
  • UUID value type - parsing (UUID.parse) of hyphenated, braced, URN, and bare-hex UUID formats, plus compareTo, equals, clone, getVariant, and getVersion.
  • Bundled CLI - npx uuidv7 [-n <count>] prints one or more UUIDv7 strings directly to stdout for scripting and ad-hoc use.
  • UUIDv4 fallback - uuidv4() / uuidv4obj() for teams that need standard random UUIDs from the same package.
  • Cross-environment RNG - automatic use of the Web Crypto API (crypto.getRandomValues) with a buffered wrapper for throughput, falling back to Math.random() only when Web Crypto is unavailable.

Common Use Cases

  • Database primary keys - engineers replacing auto-increment or UUIDv4 primary keys with UUIDv7 to get natural time-ordering and better B-tree index locality.
  • Distributed event/log IDs - services stamping events or log entries with IDs that are both globally unique and chronologically sortable without a separate timestamp column.
  • Command-line ID generation - developers or scripts using npx uuidv7 to generate one-off or bulk IDs for seed data, fixtures, or manual testing.
  • Custom per-worker generators - high-throughput systems instantiating a dedicated V7Generator per worker/request to avoid shared mutable state while preserving monotonic ordering guarantees.
  • Strict monotonicity enforcement - systems using generateOrAbort() to detect and explicitly handle significant system-clock rollbacks rather than silently accepting out-of-order IDs.

Under The Hood

Architecture The library is a single src/index.ts module built around three cooperating pieces: an immutable UUID value class wrapping a 16-byte Uint8Array with parsing/formatting/comparison methods, a V7Generator class that owns the monotonic counter and biased-timestamp state machine (generateOrAbortWithTs / generateOrResetWithTs), and a small module-level defaultGenerator singleton lazily created on first call to the top-level uuidv7()/uuidv4() convenience functions. The counter-overflow and clock-rollback handling is centralized in one method (generateOrAbortWithTs), making the increasing-order guarantee easy to audit; a separate cli.js at the package root is a thin wrapper that imports the published package and streams generated IDs to stdout via Node’s stream/promises pipeline. Changing the core UUID byte layout or the counter state machine would ripple through every public function, since all of them funnel through V7Generator.

Tech Stack Written in strict-mode TypeScript (target ES2020, module: node20) with zero runtime dependencies; the build step (tsc) emits both an ESM entry (dist/index.js) and a CommonJS entry (dist/index.cjs) for compatibility, with sideEffects: false for tree-shaking. Documentation is generated with TypeDoc, and dev dependencies are minimal (mocha for tests, typescript/typedoc). Randomness sources dispatch on environment: the Web Crypto API (crypto.getRandomValues) wrapped in a small buffering class (BufferedCryptoRandom) for browsers, Deno, and modern Node, with a Math.random() fallback guarded by an optional UUIDV7_DENY_WEAK_RNG compile-time flag.

Code Quality Tests live under test/ (uuid.test.js, uuidv7.test.js, uuidv4.test.js, gen.test.js, over 1,100 lines total) and run via mocha, covering UUID parsing/formatting round-trips, variant/version detection, and generator monotonicity including rollback scenarios. TypeScript is configured with strict: true, exactOptionalPropertyTypes, and noUncheckedSideEffectImports, giving strong compile-time guarantees. Error handling is explicit and typed (RangeError for out-of-range fields, SyntaxError for unparseable strings, TypeError for malformed byte arrays) rather than swallowed. Naming is consistent and every public method carries a TSDoc comment; there is no separate lint config beyond the TypeScript compiler and no CI workflow visible in the shallow clone.

What Makes It Unique The library’s most distinctive design choice is generateOrAbort()/generateOrAbortWithTs(), which gives callers an explicit, opt-in way to detect a significant system-clock rollback and refuse to generate an ID rather than silently breaking the monotonic ordering guarantee that most other UUIDv7 implementations only guarantee on a best-effort basis. Combined with a configurable per-generator rollbackAllowance and a 42-bit counter sized specifically to avoid overflow under realistic throughput, the implementation treats clock monotonicity as a first-class correctness concern rather than an incidental property of using a timestamp prefix.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search