NanoID Generator (Cryptographically Secure)

Generate collision-resistant, URL-friendly unique IDs using Web Crypto API CSPRNG with configurable lengths and custom alphabets.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:UUID / GUID Generator (v4 & v1) →Cron Expression Generator & Schedule Builder →Lorem Ipsum Placeholder Text Generator →HTML Entity Encoder & Decoder →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.

What is NanoID?

NanoID is a tiny, cryptographically secure, URL-friendly unique string identifier generator created by Andrey Sitnik in 2017. Designed as a modern, compact successor to traditional UUID v4, NanoID has become one of the most widely adopted unique identifier standards across the JavaScript, Node.js, Python, and Go ecosystems.

While classic UUID v4 identifiers require 36 characters (including four hyphens, such as f47ac10b-58cc-4372-a567-0e02b2c3d479), NanoID achieves comparable cryptographic collision resistance in only 21 characters (e.g., V1StGXR8_Z5jdHi6B-myT). Furthermore, its npm library footprint is just 130 bytes (minified and gzipped)—roughly 35 times smaller than the standard uuid package.

Because NanoID uses an alphabet composed exclusively of alphanumeric characters, hyphens, and underscores, its output is 100% URL-safe, eliminating the need for URL percent-encoding when used in query parameters, RESTful route paths, database primary keys, or frontend component keys.

The Affi-Chain NanoID Generator generates bulk, cryptographically secure NanoIDs directly in your browser using hardware-accelerated SubtleCrypto (crypto.getRandomValues()), with customizable ID lengths and custom alphabet dictionaries with zero network dependencies.


NanoID Architecture & Mathematical Collision Entropy

NanoID achieves its compact footprint by maximizing the information density of each character:

1. Alphabet Size & Bit Entropy

Standard UUID v4 relies on hexadecimal notation ($16$ possible characters: 0-9 and a-f), where each character carries only $4$ bits of entropy ($\log_2(16) = 4$).

In contrast, NanoID uses an expanded 64-character URL-safe alphabet: $$\text{Alphabet: } \texttt{A-Za-z0-9_- } \implies 26 + 26 + 10 + 2 = 64 \text{ characters}$$ Because $64 = 2^6$, every single character in a NanoID carries exactly 6 bits of cryptographic entropy: $$\text{Total Bit Entropy (21 chars)} = 21 \times 6 = \mathbf{126 \text{ bits of entropy}}$$ By comparison, UUID v4 carries 122 bits of random entropy. NanoID delivers greater mathematical collision safety while being $40%$ shorter.

2. Collision Probability Calculation

The probability $p$ of generating a collision among $N$ generated identifiers with alphabet size $A$ and length $L$ is modeled by the Birthday Paradox approximation:

$$p \approx 1 - \exp\left( -\frac{N(N - 1)}{2 \times A^L} \right)$$

  • At a continuous generation rate of 1,000 NanoIDs per second, it would take approximately $4.1 \text{ million years}$ to reach a $1%$ probability of generating a single collision.
  • For most web applications, generating 10,000,000 IDs guarantees a collision probability of less than $1 \text{ in } 10^{15}$.

Custom Lengths & Alphabet Presets Matrix

Depending on the operational context, engineers adjust NanoID lengths and alphabets:

Identifier ConfigurationCharacter LengthAlphabet SetTotal CombinationsIdeal Production Use Case
Standard NanoID21 charsA-Za-z0-9_- (64 chars)$\approx 7.0 \times 10^{37}$Default primary keys, user IDs, session tokens
Short Link / Slug10 charsA-Za-z0-9 (62 chars)$\approx 8.3 \times 10^{17}$URL shorteners (e.g. bit.ly/3xK9L2p), document IDs
Numeric SMS OTP6 chars0-9 (10 chars)$1,000,000$Two-factor authentication codes (short expiration)
Human-Safe (No Confusion)12 chars23456789ABCDEFGHJKLMNPQRSTUVWXYZ (32 chars)$\approx 1.15 \times 10^{18}$Physical voucher codes, phone support reference keys

Practical Code Implementation: Pure In-Browser NanoID Engine

Below is a complete, dependency-free JavaScript implementation utilizing the browser's native crypto.getRandomValues() and bitwise masking to eliminate modulo bias:

/**
 * Zero-Dependency Cryptographically Secure NanoID Generator.
 */
function generateNanoId(size = 21, alphabet = 'use-standard') {
  const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLFGQZbfghjklqvwyzICT';
  const chars = alphabet === 'use-standard' ? urlAlphabet : alphabet;
  
  const mask = (2 << (Math.log(chars.length - 1) / Math.LN2)) - 1;
  const step = Math.ceil((1.6 * mask * size) / chars.length);

  let id = '';
  while (true) {
    const bytes = new Uint8Array(step);
    crypto.getRandomValues(bytes);

    for (let i = 0; i < step; i++) {
      const byte = bytes[i] & mask;
      if (byte < chars.length) {
        id += chars[byte];
        if (id.length === size) return id;
      }
    }
  }
}

// Verification Examples:
console.log("Standard 21-char NanoID:", generateNanoId());
// Example: "V1StGXR8_Z5jdHi6B-myT"

console.log("10-char Short URL Slug:", generateNanoId(10));
// Example: "e4k9LmP2xQ"

console.log("6-digit Verification PIN:", generateNanoId(6, "0123456789"));
// Example: "849201"

Comparison Matrix: Modern Unique Identifier Frameworks

Metric / FeatureNanoIDUUID v4UUID v7 (RFC 9562)CUID2
Character Length21 chars36 chars (with hyphens)36 chars24 chars
URL Safe Out-of-Box?Yes (A-Za-z0-9_-)Requires escaping/hyphensRequires hyphensYes
Cryptographic Entropy126 bits122 bits74 random bits + timestampHigh (SHA-3 hash based)
Database Index Friendly?No (Random B-Tree thrashing)NoYes (K-Sortable timestamp)Partially
Bundle Size Overhead~130 bytes~1,200 bytes~1,500 bytes~4,000 bytes

Critical Edge Cases & Common Security Pitfalls

1. The Modulo Bias Defect in Naive Implementations

A common mistake when generating IDs with custom alphabets is using the modulo operator directly on random bytes:

// DANGEROUS! Introduces Modulo Bias!
const badChar = alphabet[randomByte % alphabet.length];

Because $256$ is not evenly divisible by non-power-of-two alphabet lengths (e.g. $62$ for alphanumeric), characters at the beginning of the alphabet have a statistically higher probability of being chosen.

  • Remediation: NanoID uses bitwise masking with rejection sampling (as shown in the implementation above), completely eliminating statistical bias.

2. Never Use Math.random()

Using Math.random() to generate unique identifiers creates predictable sequences that can be reverse-engineered by malicious actors. Always enforce crypto.getRandomValues() or Node.js crypto.randomBytes().

3. Database Indexing Trade-Offs (NanoID vs UUID v7)

Like UUID v4, standard NanoIDs are completely random. When inserted into clustered B-Tree indexes in PostgreSQL or MySQL, random insertions cause page splits.

  • For public-facing slugs, share links, and distributed client IDs, NanoID is unmatched.
  • For high-write database primary keys, consider UUID v7 or appending a timestamp prefix.

Frequently Asked Questions

Why choose NanoID over UUID v4?
NanoID is smaller (21 characters vs 36 characters in UUID), URL-friendly without hyphens, uses a larger 64-symbol alphabet, and provides equivalent collision safety.

Explore Related Utilities