Tiny and Fast Unique ID Generator

2.0.2 · active · verified Sun Apr 19

The `uid` package provides a highly optimized and compact utility for generating fixed-length random unique IDs in JavaScript environments, supporting both Node.js and browsers. The current stable version is 2.0.2, with releases focusing on performance, bug fixes, and TypeScript compatibility, indicating an active maintenance and development cadence. Key differentiators include its extremely small footprint (130B to 205B gzipped) and high performance, with benchmarks showing it to be significantly faster than alternatives like `nanoid` in its default non-secure mode. It offers three distinct modes: `uid` (fast, `Math.random`-based, non-secure), `uid/secure` (cryptographically secure via `crypto.getRandomValues`), and `uid/single` (non-secure, no internal cache, ideal for short-lived environments). This flexibility allows developers to choose the appropriate balance of speed, security, and bundle size for their specific use case.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use the default, secure, and single-use `uid` generators with custom lengths.

import { uid } from 'uid';
import { uid as secureUid } from 'uid/secure';
import { uid as singleUid } from 'uid/single';

// Generate a default non-secure ID (length 11, hexadecimal alphabet)
const id1 = uid();
console.log(`Default non-secure ID: ${id1}`); // e.g., 'c92054d1dd6'

// Generate a non-secure ID with custom length
const id2 = uid(16);
console.log(`Non-secure ID (length 16): ${id2}`); // e.g., '8234dbf9a7dcec3b'

// Generate a cryptographically secure ID (length 11, hexadecimal alphabet)
// Requires crypto.getRandomValues() support (Node.js & modern browsers)
const secureId = secureUid();
console.log(`Secure ID: ${secureId}`); // e.g., 'f8a4b6c1e9d0a2b'

// Generate a single-use ID (length 11, alphanumeric alphabet)
// Does not maintain an internal buffer, good for ephemeral contexts
const singleUseId = singleUid();
console.log(`Single-use ID: ${singleUseId}`); // e.g., 'aG5jK7lP2qR'

// Example of generating multiple IDs within a loop
for (let i = 0; i < 3; i++) {
  console.log(`Loop ID ${i}: ${uid(8)}`);
}

view raw JSON →