# Nano ID **English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) A tiny, secure, URL-friendly, unique string ID generator for JavaScript. > “An amazing level of senseless perfectionism, > which is simply impossible not to respect.” * **Small.** 130 bytes (minified and gzipped). No dependencies. [Size Limit] controls the size. * **Fast.** It is 2 times faster than UUID. * **Safe.** It uses hardware random generator. Can be used in clusters. * **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). So ID size was reduced from 36 to 21 symbols. * **Portable.** Nano ID was ported to [20 programming languages](#other-programming-languages). ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` Supports modern browsers, IE [with Babel], Node.js and React Native. [online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ [with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ [Size Limit]: https://github.com/ai/size-limit ## Table of Contents * [Comparison with UUID](#comparison-with-uuid) * [Benchmark](#benchmark) * [Security](#security) * [API](#api) * [Blocking](#blocking) * [Async](#async) * [Non-Secure](#non-secure) * [Custom Alphabet or Size](#custom-alphabet-or-size) * [Custom Random Bytes Generator](#custom-random-bytes-generator) * [Usage](#usage) * [IE](#ie) * [React](#react) * [React Native](#react-native) * [Rollup](#rollup) * [PouchDB and CouchDB](#pouchdb-and-couchdb) * [Mongoose](#mongoose) * [Web Workers](#web-workers) * [CLI](#cli) * [Other Programming Languages](#other-programming-languages) * [Tools](#tools) ## 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 three 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 code is **4 times less** than `uuid/v4` package: 130 bytes instead of 483. 3. Because of memory allocation tricks, Nano ID is **2 times** faster than UUID. ## Benchmark ```rust $ node ./test/benchmark.js crypto.randomUUID 25,603,857 ops/sec @napi-rs/uuid 9,973,819 ops/sec uid/secure 8,234,798 ops/sec @lukeed/uuid 7,464,706 ops/sec nanoid 5,616,592 ops/sec customAlphabet 3,115,207 ops/sec uuid v4 1,535,753 ops/sec secure-random-string 388,226 ops/sec uid-safe.sync 363,489 ops/sec cuid 187,343 ops/sec shortid 45,758 ops/sec Async: nanoid/async 96,094 ops/sec async customAlphabet 97,184 ops/sec async secure-random-string 92,794 ops/sec uid-safe 90,684 ops/sec Non-secure: uid 67,376,692 ops/sec nanoid/non-secure 2,849,639 ops/sec rndm 2,674,806 ops/sec ``` Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 34, Node.js 16.10. ## Security *See a good article about random generators theory: [Secure random values (in Node.js)]* * **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano ID uses the `crypto` module in Node.js and the Web Crypto API in browsers. These modules use unpredictable hardware random generator. * **Uniformity.** `random % alphabet` is a popular mistake to make when coding an ID generator. The distribution will not be even; there will be a lower chance for some symbols to appear compared to others. So, it will reduce the number of tries when brute-forcing. Nano ID uses a [better algorithm] and is tested for uniformity. * **Well-documented:** all Nano ID hacks are documented. See comments in [the source]. * **Vulnerabilities:** to report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. [Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba [better algorithm]: https://github.com/ai/nanoid/blob/main/index.js [the source]: https://github.com/ai/nanoid/blob/main/index.js ## Install ```bash npm install --save nanoid ``` 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. ```js import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js' ``` Nano ID provides ES modules. You do not need to do anything to use Nano ID as ESM in webpack, Rollup, Parcel, or Node.js. ```js import { nanoid } from 'nanoid' ``` In Node.js you can use CommonJS import: ```js const { nanoid } = require('nanoid') ``` ## API Nano ID has 3 APIs: normal (blocking), asynchronous, and non-secure. 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). ### Blocking The safe and easiest way to use Nano ID. In rare cases could block CPU from other work while noise collection for hardware random generator. ```js 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. ```js 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](#custom-alphabet-or-size) or a [random generator](#custom-random-bytes-generator). [ID collision probability]: https://zelark.github.io/nano-id-cc/ ### Async To generate hardware random bytes, CPU collects electromagnetic noise. For most cases, entropy will be already collected. In the synchronous API during the noise collection, the CPU is busy and cannot do anything useful (for instance, process another HTTP request). Using the asynchronous API of Nano ID, another code can run during the entropy collection. ```js import { nanoid } from 'nanoid/async' async function createUser () { user.id = await nanoid() } ``` Read more about entropy collection in [`crypto.randomBytes`] docs. Unfortunately, you will lose Web Crypto API advantages in a browser if you use the asynchronous API. So, currently, in the browser, you are limited with either security (`nanoid`), asynchronous behavior (`nanoid/async`), or non-secure behavior (`nanoid/non-secure`) that will be explained in the next part of the documentation. [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback ### Non-Secure By default, Nano ID uses hardware random bytes generation for security and low collision probability. If you are not so concerned with security, you can use the faster non-secure generator. ```js import { nanoid } from 'nanoid/non-secure' const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" ``` ### Custom Alphabet or Size `customAlphabet` allows you to create `nanoid` with your own alphabet and ID size. ```js import { customAlphabet } from 'nanoid' const nanoid = customAlphabet('1234567890abcdef', 10) model.id = nanoid() //=> "4f90d13a42" ``` ```js import { customAlphabet } from 'nanoid/async' const nanoid = customAlphabet('1234567890abcdef', 10) async function createUser () { user.id = await nanoid() } ``` ```js 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 256 symbols or less. Otherwise, the security of the internal generator algorithm is not guaranteed. In addition to setting a default size, you can change the ID size when calling the function: ```js import { customAlphabet } from 'nanoid' const nanoid = customAlphabet('1234567890abcdef', 10) model.id = nanoid(5) //=> "f01a2" ``` [ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/ [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary ### 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: ```js 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`. ```js const { customRandom, urlAlphabet } = require('nanoid') const nanoid = customRandom(urlAlphabet, 10, random) ``` Asynchronous and non-secure APIs are not available for `customRandom`. 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. ## Usage ### IE If you support IE, you need to [transpile `node_modules`] by Babel and add `crypto` alias. Moreover, `UInt8Array` in IE actually is not an array and to cope with it, you have to convert it to an array manually: ```js // polyfills.js if (!window.crypto && window.msCrypto) { window.crypto = window.msCrypto const getRandomValuesDef = window.crypto.getRandomValues window.crypto.getRandomValues = function (array) { const values = getRandomValuesDef.call(window.crypto, array) const result = [] for (let i = 0; i < array.length; i++) { result[i] = values[i]; } return result }; } ``` ```js import './polyfills.js' import { nanoid } from 'nanoid' ``` [transpile `node_modules`]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ ### React There’s no correct way to use Nano ID for React `key` prop since it should be consistent among renders. ```jsx function Todos({todos}) { return (