Nano ID

一个用于JavaScript的小巧、安全、URL友好、唯一的字符串ID生成器。

README

Nano ID


Nano ID logo by Anton Lovchikov


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.
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

  1. ``` js
  2. import { nanoid } from 'nanoid'
  3. model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
  4. ```

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

  <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
       alt="Sponsored by Evil Martians" width="236" height="54">

Table of Contents


  Async
  React
  Jest
  CLI


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 smaller than uuid/v4 package:
   130 bytes instead of 423.


Benchmark


  1. ```rust
  2. $ node ./test/benchmark.js
  3. crypto.randomUUID         21,119,429 ops/sec
  4. uuid v4                   20,368,447 ops/sec
  5. @napi-rs/uuid             11,493,890 ops/sec
  6. uid/secure                 8,409,962 ops/sec
  7. @lukeed/uuid               6,871,405 ops/sec
  8. nanoid                     5,652,148 ops/sec
  9. customAlphabet             3,565,656 ops/sec
  10. secure-random-string         394,201 ops/sec
  11. uid-safe.sync                393,176 ops/sec
  12. cuid                         208,131 ops/sec
  13. shortid                       49,916 ops/sec

  14. Async:
  15. nanoid/async                 135,260 ops/sec
  16. async customAlphabet         136,059 ops/sec
  17. async secure-random-string   135,213 ops/sec
  18. uid-safe                     119,587 ops/sec

  19. Non-secure:
  20. uid                       58,860,241 ops/sec
  21. nanoid/non-secure          2,744,615 ops/sec
  22. rndm                       2,718,063 ops/sec
  23. ```

Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 36, Node.js 18.9.


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.

  <img src="img/distribution.png" alt="Nano ID uniformity"
     width="340" height="135">

Well-documented: all Nano ID hacks are documented. See comments
  in [the source].
Vulnerabilities: to report a security vulnerability, please use
  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


  1. ``` sh
  2. npm install --save nanoid
  3. ```

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.

  1. ``` js
  2. import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
  3. ```

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.

  1. ``` js
  2. import { nanoid } from 'nanoid'
  3. ```


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.

  1. ``` js
  2. import { nanoid } from 'nanoid'
  3. model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
  4. ```

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

  1. ``` js
  2. nanoid(10) //=> "IRFa-VaY2b"
  3. ```

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

You can also use a custom alphabet

[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.

  1. ``` js
  2. import { nanoid } from 'nanoid/async'

  3. async function createUser() {
  4.   user.id = await nanoid()
  5. }
  6. ```

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.

  1. ``` js
  2. import { nanoid } from 'nanoid/non-secure'
  3. const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
  4. ```


Custom Alphabet or Size


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

  1. ``` js
  2. import { customAlphabet } from 'nanoid'
  3. const nanoid = customAlphabet('1234567890abcdef', 10)
  4. model.id = nanoid() //=> "4f90d13a42"
  5. ```

  1. ``` js
  2. import { customAlphabet } from 'nanoid/async'
  3. const nanoid = customAlphabet('1234567890abcdef', 10)
  4. async function createUser() {
  5.   user.id = await nanoid()
  6. }
  7. ```

  1. ``` js
  2. import { customAlphabet } from 'nanoid/non-secure'
  3. const nanoid = customAlphabet('1234567890abcdef', 10)
  4. user.id = nanoid()
  5. ```

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:

  1. ``` js
  2. import { customAlphabet } from 'nanoid'
  3. const nanoid = customAlphabet('1234567890abcdef', 10)
  4. model.id = nanoid(5) //=> "f01a2"
  5. ```

[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:

  1. ``` js
  2. import { customRandom } from 'nanoid'

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

  7. nanoid() //=> "fbaefaadeb"
  8. ```

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.

  1. ``` js
  2. const { customRandom, urlAlphabet } = require('nanoid')
  3. const nanoid = customRandom(urlAlphabet, 10, random)
  4. ```

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


React


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

  1. ``` js
  2. function Todos({todos}) {
  3.   return (
  4.     <ul>
  5.       {todos.map(todo => (
  6.         <li key={nanoid()}> /* DON’T DO IT */
  7.           {todo.text}
  8.         </li>
  9.       ))}
  10.     </ul>
  11.   )
  12. }
  13. ```

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

  1. ``` js
  2. const todoItems = todos.map((todo) =>
  3.   <li key={todo.id}>
  4.     {todo.text}
  5.   </li>
  6. )
  7. ```

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

  1. ``` js
  2. const todoItems = todos.map((text, index) =>
  3.   <li key={index}> /* Still not recommended but preferred over nanoid().
  4.                       Only do this if items have no stable IDs. */
  5.     {text}
  6.   </li>
  7. )
  8. ```

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.

[useId]: https://reactjs.org/docs/hooks-reference.html#useid


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.

  1. ``` js
  2. import 'react-native-get-random-values'
  3. import { nanoid } from 'nanoid'
  4. ```

[react-native-get-random-values]: https://github.com/LinusU/react-native-get-random-values


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:

  1. ``` js
  2. db.put({
  3.   _id: 'id' + nanoid(),
  4.   
  5. })
  6. ```


Web Workers


Web Workers do not have access to a secure random generator.

Security is important in IDs when IDs should be unpredictable.
For instance, in "access by URL" link generation.
If you do not need unpredictable IDs, but you need to use Web Workers,
you can use the non‑secure ID generator.

  1. ``` js
  2. import { nanoid } from 'nanoid/non-secure'
  3. nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
  4. ```

Note: non-secure IDs are more prone to collision attacks.


Jest


Jest test runner with jest-environment-jsdom will use browser’s version
of Nano ID. You will need polyfill for Web Crypto API.

  1. ``` js
  2. import { randomFillSync } from 'crypto'

  3. window.crypto = {
  4.   getRandomValues(buffer) {
  5.     return randomFillSync(buffer)
  6.   }
  7. }
  8. ```


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.

  1. ```sh
  2. $ npx nanoid
  3. npx: installed 1 in 0.63s
  4. LZfXLFzPPR4NNrgjlWDxn
  5. ```

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

  1. ```sh
  2. $ npx nanoid --size 10
  3. L3til0JS4z
  4. ```

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

  1. ```sh
  2. $ npx nanoid --alphabet abc --size 15
  3. bccbcabaabaccab
  4. ```

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.

  with dictionaries
Postgres Extension
R (with dictionaries)

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

[CLI]: #cli


Tools


[ID size calculator] shows collision probability when adjusting
  the ID alphabet or size.
[nanoid-dictionary] with popular alphabets to use with [customAlphabet].
[nanoid-good] to be sure that your ID doesn’t contain any obscene words.

[nanoid-dictionary]: https://github.com/CyberAP/nanoid-dictionary
[ID size calculator]:  https://zelark.github.io/nano-id-cc/
[customAlphabet]:    #custom-alphabet-or-size
[nanoid-good]:       https://github.com/y-gagar1n/nanoid-good