Skip to content

nats-io/nuid.js

Repository files navigation

Nuid.js

License node deno coverage JSDoc

JSR JSR

npm npm npm

A highly performant unique identifier generator for JavaScript.

Installation

Deno (via JSR):

deno add jsr:@nats-io/nuid
import { Nuid, nuid } from "jsr:@nats-io/nuid";

Node / Bun (via npm):

npm install @nats-io/nuid
// `nuid` is a shared global instance — call `next()` on it directly.
// `Nuid` is the class — use `new Nuid()` for an isolated instance.
const { nuid, Nuid } = require("@nats-io/nuid");
// or
import { Nuid, nuid } from "@nats-io/nuid";

Basic Usage

// To generate a bunch of nuids:
let id = nuid.next();
id = nuid.next();
//

// To generate a new prefix:
nuid.reset();
// the prefix is also re-randomized automatically when the sequence
// counter overflows (i.e. reaches 62^10).
id = nuid.next();

Format

A NUID is 22 base-62 ASCII characters from the alphabet 0-9A-Za-z:

  • 12-char prefix — drawn from crypto.getRandomValues (entropy-friendly: one draw per instance, not per id). Per-prefix space is 62^12 ≈ 3.2×10^21.
  • 10-char sequence — starts at a pseudo-random offset and advances by a pseudo-random increment in [33, 332] on each next(). The sequence numerically caps at 62^10; combined with the per-instance increment, that yields roughly 62^10 / inc ids per prefix (~10^15) before the prefix is re-randomized.

Total identifier space is 62^22 ≈ 2.7×10^39.

Output format matches the Go nats-io/nuid reference — same alphabet, same length — so JS-generated nuids look the same as Go-generated ones.

Migration

From 2.x to 3.x: the public API is unchanged, and output is still 22 chars. However, generated ids now use the full base-62 alphabet (0-9A-Za-z) matching the Go nats-io/nuid reference, so any caller that validates, stores, or compares against the old uppercase-only [0-9A-Z]{22} format should update that logic before upgrading.

The 3.x version of the npm module supports both CJS and ESM. An ESM-only version of the module is available via jsr @nats-io/nuid.

Supported Node Versions

Minimum supported Node.js version is set in package.json (engines.node), currently >= 22. The version policy tracks Node.js release support: supported floor moves up as older LTS lines reach end-of-life. CI runs against the latest current release.

License

Unless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.

About

A Node.js implementation of NUID

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

 
 
 

Contributors