@wuyuchentr/uuid-v7
v1.0.0
Published
Generate UUID v7 (time-ordered + random) — pure JS, no deps, < 1KB.
Maintainers
Readme
@wuyuchentr/uuid-v7
Generate UUID v7 (time-ordered + random) — pure JS, zero dependencies, < 1 KB.
UUID v7 is the time-sorted UUID standard (RFC 9562). Unlike v4 (fully random), v7 has a 48-bit Unix ms timestamp prefix, making it monotonically increasing and friendly to database indexes (B-trees).
Install
npm install @wuyuchentr/uuid-v7Usage
const { generate } = require('@wuyuchentr/uuid-v7');
console.log(generate());
// → 018f9f2f-2a8c-7a00-b000-123456789abcCompared to UUID v4
| | UUID v4 | UUID v7 |
|------------|----------------------------------|--------------------------------------|
| Ordering | Random (bad for DB index) | Time-sorted (B-tree friendly) |
| Sortable | No | Yes — order by creation time |
| Structure | xxxxxxxx-xxxx-4xxx-xxxx* | tttttttt-tttt-7xxx-axxx-xxxxxxxx* |
How it works
- 48-bit timestamp (milliseconds since epoch)
- 4-bit version (
0111= 7) - 12-bit monotonic sequence counter (per-millisecond, for sub-ms ordering)
- 2-bit variant (
10) - 62 bits of random entropy
Uses crypto.getRandomValues() (browser / Node 15+) with a fallback to require('crypto').randomBytes() for older Node.js.
API
generate() → string
Returns a UUID v7 string.
const id = generate();
// "018f9f2f-2a8c-7a00-b000-123456789abc"