Nano ID

repository·main·Indexed 12 days ago

https://github.com/ai/nanoid

A tiny (118 bytes), secure, and URL-friendly unique string ID generator for JavaScript. Version 6.0.1 provides a faster and more compact alternative to UUID v4 with similar collision resistance. Features include a CLI for terminal generation, support for custom alphabets via `customAlphabet()`, custom randomness sources via `customRandom()`, and a non-secure version for environments without hardware random generators.

Tokens
10.9K
Snippets
64
Records
66
Agent score
96%

What's inside Nano ID

  1. Overview of Nano ID

    main

    Nano ID is a lightweight, secure, and fast unique ID generator for JavaScript. It is designed to be URL-friendly and can be used in various environments including modern browsers, Node.js, React Native, and even older IE (via Babel).

    Key features:

    • Lightweight: ~118 bytes (minified + Brotli) with zero dependencies.
    • Fast: Significantly faster than native crypto.randomUUID().
    • Secure: Uses hardware-based random number generators (Web Crypto API in browsers, crypto module in Node.js).
    • Compact: Uses a larger alphabet (A-Za-z0-9_-) than UUID, allowing for a shorter ID length (21 characters) while maintaining similar collision resistance (126 bits of randomness vs 122 bits in UUID).
    import { nanoid } from 'nanoid'
    model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
  2. Nano ID Ecosystem and Tools

    main

    Supported Languages

    Nano ID is available in many languages (C#, C++, Go, Java, Python, Rust, etc.), allowing for consistent ID generation across client-side and server-side environments.

    Useful Tools

    • ID Size Calculator: Calculates collision probability based on alphabet and size configurations.
    • nanoid-dictionary: Provides popular alphabets for use with customAlphabet.
    • nanoid-good: Ensures generated IDs do not contain offensive or inappropriate words.
  3. Avoid using Nano ID for React keys

    main

    Do not use nanoid() directly inside a React key prop. Because key must be consistent across renders, generating a new random ID on every render will cause performance issues and state loss.

    Instead, use a stable ID from your data. If no stable ID is available, using the array index is preferred over nanoid() for keys, though still not ideal.

    If you only need a random ID to associate elements (like a label and an input field), use React's built-in useId hook instead.

    // ❌ DO NOT DO THIS
    {todos.map(todo => (
      <li key={nanoid()}>
        {todo.text}
      </li>
    ))}
    
    // ✅ DO THIS (use stable IDs)
    {todos.map(todo => (
      <li key={todo.id}>
        {todo.text}
      </li>
    ))}
    
    // ✅ OR THIS (if no stable ID exists, index is better than nanoid() for keys)
    {todos.map((text, index) => (
      <li key={index}>
        {text}
      </li>
    ))}
  4. Avoid using Nano ID as React keys

    main

    Do not use nanoid() directly inside a map function to generate key props in React components. Because nanoid() generates a new ID on every render, it breaks React's reconciliation process, leading to performance issues and state bugs.

    Instead, use a stable ID from your data. If no stable ID exists, using the array index is preferred over generating a new Nano ID on every render.

    // ❌ DO NOT DO THIS
    {todos.map(todo => (
      <li key={nanoid()}>
        {todo.text}
      </li>
    ))}
    
    // ✅ DO THIS (Use stable IDs)
    {todos.map(todo => (
      <li key={todo.id}>
        {todo.text}
      </li>
    ))}
    
    // ✅ OR THIS (Use index if no stable IDs exist; better than nanoid() in render)
    {todos.map((text, index) => (
      <li key={index}>
        {text}
      </li>
    ))}
  5. Use Nano ID with PouchDB and CouchDB

    main

    In PouchDB and CouchDB, document IDs cannot start with an underscore (_). Since Nano ID can potentially start with an underscore, you should add a prefix to your generated IDs to ensure compatibility.

    db.put({
      _id: 'id' + nanoid(),
      ...
    })
  6. Use Nano ID with PouchDB or CouchDB

    main

    In PouchDB and CouchDB, document IDs cannot start with an underscore (_). Since Nano ID might generate an ID starting with _ by default, you should add a prefix to your IDs to avoid conflicts.

    db.put({
      _id: 'id' + nanoid(),
      ...
    })
  7. Setup Nano ID in React Native

    main

    React Native does not have a built-in random number generator. To use Nano ID in React Native or Expo (version 39.x or later), you must use a polyfill.

    1. Install react-native-get-random-values.
    2. Import the polyfill before importing nanoid.
    import 'react-native-get-random-values'
    import { nanoid } from 'nanoid'
  8. Prevent ID conflicts in PouchDB and CouchDB

    main

    PouchDB and CouchDB do not allow IDs to start with an underscore (_). Since Nano ID may generate IDs starting with _, you should add a prefix to your IDs to ensure compatibility.

    db.put({
      _id: 'id' + nanoid(),
      ...
    })
  9. Prevent ID collisions in PouchDB and CouchDB

    main

    In PouchDB and CouchDB, document IDs cannot start with an underscore _. Since Nano ID may start with an underscore by default, you should add a prefix to your IDs to ensure compatibility.

    db.put({
      _id: 'id' + nanoid(),
      ...
    })
  10. Setup Nano ID in React Native or Expo

    main

    React Native does not have a built-in random number generator. To use Nano ID in plain React Native or Expo (starting from version 39.x), you must install and import react-native-get-random-values before importing nanoid.

    import 'react-native-get-random-values'
    import { nanoid } from 'nanoid'
  11. Use Nano ID via CDN

    main

    For rapid prototyping, you can import Nano ID directly from a CDN without a local installation. Note: Do not use this method for production websites as it negatively impacts loading speed.

    import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'