nanoid README

The project's README from github.com/ai/nanoid. As one markdown file: README.md.

Nano ID

Nano ID logo by Anton Lovchikov

English | 日本語 | Русский | 简体中文 | Bahasa Indonesia | 한국어 | العربية

A tiny, secure, URL-friendly, unique string ID generator for JavaScript.

“An amazing level of senseless perfectionism, which is simply impossible not to respect.”

import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"

  Nano ID is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.


Table of Contents

Comparison with UUID

Nano ID is quite comparable to UUID v4 (random-based). It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability:

For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.

There are two main differences between Nano ID and UUID v4:

  1. Nano ID uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.
  2. Nano ID is faster than crypto.randomUUID and uuid/v4.

Benchmark

$ node ./test/benchmark.js
nope-id                 20,386,830 ops/sec
nanoid                  20,434,827 ops/sec
customAlphabet          20,544,476 ops/sec
crypto.randomUUID       12,865,759 ops/sec
uuid v4                  7,930,104 ops/sec
@napi-rs/uuid            5,573,171 ops/sec
uid/secure               6,308,267 ops/sec
@lukeed/uuid             5,278,597 ops/sec
nanoid for browser         311,497 ops/sec
secure-random-string       301,667 ops/sec
uid-safe.sync              297,815 ops/sec

Non-secure:
uid                     20,286,757 ops/sec
nanoid/non-secure        2,397,594 ops/sec
rndm                     2,445,462 ops/sec

Security

See a good article about random generators theory: Secure random values (in Node.js)

Install

npm install nanoid

JSR

JSR is a replacement for npm with open governance and active development (in contrast to npm).

npx jsr add @sitnik/nanoid

You can use it in Node.js, Deno, Bun, etc.

// Replace `nanoid` to `@sitnik/nanoid` in all imports
import { nanoid } from '@sitnik/nanoid'

For Deno install it by deno add jsr:@sitnik/nanoid or import from jsr:@sitnik/nanoid.

CDN

For quick hacks, you can load Nano ID from CDN. Though, it is not recommended to be used in production because of the lower loading performance.

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

API

By default, Nano ID uses URL-friendly symbols (A-Za-z0-9_-) and returns an ID with 21 characters (to have a collision probability similar to UUID v4).

import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"

If you want to reduce the ID size (and increase collisions probability), you can pass the size as an argument.

nanoid(10) //=> "IRFa-VaY2b"

Don’t forget to check the safety of your ID size in our ID collision probability calculator.

You can also use a custom alphabet or a random generator.

Custom Alphabet or Size

customAlphabet returns a function that allows you to create nanoid with your own alphabet and ID size.

import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid() //=> "4f90d13a42"
import { customAlphabet } from 'nanoid/non-secure'
const nanoid = customAlphabet('1234567890abcdef', 10)
user.id = nanoid()

Check the safety of your custom alphabet and ID size in our ID collision probability calculator. For more alphabets, check out the options in nanoid-dictionary.

Alphabet must contain from 1 to 256 symbols. Otherwise, the security of the internal generator algorithm is not guaranteed, and a generator built from an empty or over-256-symbol alphabet can loop forever instead of returning an ID.

In addition to setting a default size, you can change the ID size when calling the function:

import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid(5) //=> "f01a2"

Custom Random Bytes Generator

customRandom allows you to create a nanoid and replace alphabet and the default random bytes generator.

In this example, a seed-based generator is used:

import { customRandom } from 'nanoid'

const rng = seedrandom(seed)
const nanoid = customRandom('abcdef', 10, size => {
  return new Uint8Array(size).map(() => 256 * rng())
})

nanoid() //=> "fbaefaadeb"

random callback must accept the array size and return an array with random numbers.

If you want to use the same URL-friendly symbols with customRandom, you can get the default alphabet using the urlAlphabet.

import { customRandom, urlAlphabet } from 'nanoid'
const nanoid = customRandom(urlAlphabet, 10, random)

Note, that between Nano ID versions we may change random generator call sequence. If you are using seed-based generators, we do not guarantee the same result.

Non-Secure

Nano ID uses hardware random bytes generation for security and low collision probability. If you are not so concerned with security, you can use it for environments without hardware random generators.

import { nanoid } from 'nanoid/non-secure'
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"

Note, that non-secure version is slower than secure. Use it only if you have to.

Usage

React

There’s no correct way to use Nano ID for React key prop since it should be consistent among renders.

function Todos({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={nanoid()}>
          {' '}
          /* DON’T DO IT */
          {todo.text}
        </li>
      ))}
    </ul>
  )
}

You should rather try to reach for stable ID inside your list item.

const todoItems = todos.map(todo => <li key={todo.id}>{todo.text}</li>)

In case you don’t have stable IDs you'd rather use index as key instead of nanoid():

const todoItems = todos.map((text, index) => (
  <li key={index}>
    {' '}
    /* Still not recommended but preferred over nanoid(). Only do this if items
    have no stable IDs. */
    {text}
  </li>
))

In case you just need random IDs to link elements like labels and input fields together, useId is recommended. That hook was added in React 18.

React Native

React Native does not have built-in random generator. The following polyfill works for plain React Native and Expo starting with 39.x.

  1. Check react-native-get-random-values docs and install it.
  2. Import it before Nano ID.
import 'react-native-get-random-values'
import { nanoid } from 'nanoid'

PouchDB and CouchDB

In PouchDB and CouchDB, IDs can’t start with an underscore _. A prefix is required to prevent this issue, as Nano ID might use a _ at the start of the ID by default.

Override the default ID with the following option:

db.put({
  _id: 'id' + nanoid(),
  …
})

CLI

You can get unique ID in terminal by calling npx nanoid. You need only Node.js in the system. You do not need Nano ID to be installed anywhere.

$ npx nanoid
npx: installed 1 in 0.63s
LZfXLFzPPR4NNrgjlWDxn

Size of generated ID can be specified with --size (or -s) option:

$ npx nanoid --size 10
L3til0JS4z

Custom alphabet can be specified with --alphabet (or -a) option (note that in this case --size is required):

$ npx nanoid --alphabet abc --size 15
bccbcabaabaccab

TypeScript

Nano ID allows casting generated strings into opaque strings in TypeScript. For example:

declare const userIdBrand: unique symbol
type UserId = string & { [userIdBrand]: true }

// Use explicit type parameter:
mockUser(nanoid<UserId>())

interface User {
  id: UserId
  name: string
}

const user: User = {
  // Automatically casts to UserId:
  id: nanoid(),
  name: 'Alice'
}

Other Programming Languages

Nano ID was ported to many languages. You can use these ports to have the same ID generator on the client and server side.

For other environments, CLI is available to generate IDs from a command line.

Tools

nanoid (ai/nanoid)

Searching Database…

27.1K ·GitHub
这是什么?Nano ID 是一个体积很小、安全、适合放进 URL 的 JavaScript 唯一字符串 ID 生成器,生成的 ID 长度为 21 个字符,碰撞概率与 UUID v4 相近。
这是个库,还是我也能在命令行里运行它?它主要是一个可以导入到代码中使用的 JavaScript 库,但也提供了命令行工具(CLI),无需安装即可通过 npx 运行。
我该怎么安装并开始生成 ID?可以通过 npm 或 JSR(适用于 Deno/Bun)安装,然后导入 nanoid() 并调用它;如果只想在终端里临时生成一个 ID,直接运行 npx nanoid 即可。
它需要额外的包才能工作吗?不需要,Nano ID 没有任何依赖,经过压缩并用 brotli 处理后仅 118 字节;不过在 React Native 中还需要额外安装 react-native-get-random-values polyfill 补丁,因为它本身没有内置随机数生成器。
用自定义字符集的时候有什么要注意的吗?自定义字符集必须包含 1 到 256 个符号;超出这个范围,生成器的安全性无法保证,甚至可能陷入死循环,而不是返回一个 ID。
在浏览器、Node、Deno 和 React Native 中,它的表现都一样吗?在 Node、Deno、Bun 和浏览器中都可以用(通过 npm、JSR 或 CDN 引入);React Native 没有内置随机数生成器,所以需要额外的 polyfill 补丁。
为什么 Nano ID 比 crypto.randomUUID() 快?它使用了更大的字符集(A-Za-z0-9-),用 21 个字符就能容纳相当于 36 个字符的随机量,README 称这使它比原生的 crypto.randomUUID() 快 50%。
Nano ID 能在 JavaScript 之外使用吗?可以,它已被移植到 20 多种编程语言中,包括 Go、Rust、Python、Java、Swift 等等,因此你可以在客户端和服务端之间生成相互匹配的 ID。
有没有非安全模式或基于种子的模式?有。customRandom 允许你接入自己的随机字节生成器(例如基于种子的生成器);此外还提供一个非安全构建版本,适用于没有硬件随机数生成器的环境,不过速度较慢。
What are similar projects?npm-check-updates, hono, zx, yargs, deno, hqtui, sharp, twinkleplop
Creator
ai
Size
5.9 MB
Stars
27.1K
Age
9y
Commits · 90 Days