Introduction
Nanoid generates unique string IDs that are URL-safe, compact, and cryptographically strong. At only 118 bytes minified and brotlied with zero dependencies, it serves as a lighter and shorter alternative to UUID v4 while maintaining a comparable collision probability.
What Nanoid Does
- Generates secure random IDs using the hardware random number generator
- Produces 21-character IDs by default using a URL-safe alphabet (A-Za-z0-9_-)
- Supports custom alphabet and ID length through the customAlphabet function
- Provides a non-secure variant for performance-sensitive, non-cryptographic use cases
- Works in Node.js, browsers, Deno, Bun, and React Native environments
Architecture Overview
Nanoid reads bytes from crypto.getRandomValues (browser) or crypto.randomBytes (Node.js), then maps those bytes to a 64-character URL-safe alphabet using a bitmask-based uniform distribution algorithm. This avoids modulo bias, ensuring every character in the alphabet has equal probability.
Self-Hosting & Configuration
- Install via npm, yarn, or pnpm:
npm install nanoid - Import as ESM:
import { nanoid } from 'nanoid' - Adjust ID length:
nanoid(10)for a 10-character ID - Use
customAlphabetto define your own character set and length - For non-cryptographic contexts, import from
nanoid/non-securefor faster generation
Key Features
- 118 bytes minified and brotlied with zero dependencies
- Uses cryptographically strong random values by default
- Shorter IDs than UUID (21 vs 36 chars) with similar collision probability
- Ported to over 20 languages including Python, Go, Rust, Ruby, and Java
- Works across all major JS runtimes without polyfills
Comparison with Similar Tools
- UUID (uuid package) — 36-character output, widely recognized format; larger and not URL-safe by default
- cuid2 — collision-resistant IDs for horizontal scaling; larger output, more opinionated
- ULID — sortable 26-char IDs with timestamp prefix; not cryptographically random
- shortid — deprecated predecessor; smaller alphabet, less secure
- crypto.randomUUID() — built-in browser API; UUID v4 only, 36 characters
FAQ
Q: Is Nanoid safe for database primary keys? A: Yes. With default settings the collision probability is negligible for practical workloads; you would need to generate roughly one billion IDs per second for 34 years to reach a 1% chance of a single collision.
Q: Can I generate IDs with only lowercase letters and numbers?
A: Yes. Use customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 12) to get 12-char lowercase alphanumeric IDs.
Q: Does Nanoid support SSR frameworks like Next.js? A: Yes. Since it uses standard crypto APIs available in both Node.js and browsers, it works seamlessly in server and client components.
Q: How does Nanoid compare to UUID v4 in collision probability? A: Nanoid uses 126 bits of randomness versus UUID v4 with 122 bits, giving Nanoid a slightly lower collision probability despite shorter output.