You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

554 lines
16 KiB

3 months ago
  1. # Nano ID
  2. <img src="https://ai.github.io/nanoid/logo.svg" align="right"
  3. alt="Nano ID logo by Anton Lovchikov" width="180" height="94">
  4. **English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
  5. A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
  6. > “An amazing level of senseless perfectionism,
  7. > which is simply impossible not to respect.”
  8. * **Small.** 130 bytes (minified and gzipped). No dependencies.
  9. [Size Limit] controls the size.
  10. * **Fast.** It is 2 times faster than UUID.
  11. * **Safe.** It uses hardware random generator. Can be used in clusters.
  12. * **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
  13. So ID size was reduced from 36 to 21 symbols.
  14. * **Portable.** Nano ID was ported
  15. to [20 programming languages](#other-programming-languages).
  16. ```js
  17. import { nanoid } from 'nanoid'
  18. model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
  19. ```
  20. Supports modern browsers, IE [with Babel], Node.js and React Native.
  21. [online tool]: https://gitpod.io/#https://github.com/ai/nanoid/
  22. [with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
  23. [Size Limit]: https://github.com/ai/size-limit
  24. <a href="https://evilmartians.com/?utm_source=nanoid">
  25. <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
  26. alt="Sponsored by Evil Martians" width="236" height="54">
  27. </a>
  28. ## Table of Contents
  29. * [Comparison with UUID](#comparison-with-uuid)
  30. * [Benchmark](#benchmark)
  31. * [Security](#security)
  32. * [API](#api)
  33. * [Blocking](#blocking)
  34. * [Async](#async)
  35. * [Non-Secure](#non-secure)
  36. * [Custom Alphabet or Size](#custom-alphabet-or-size)
  37. * [Custom Random Bytes Generator](#custom-random-bytes-generator)
  38. * [Usage](#usage)
  39. * [IE](#ie)
  40. * [React](#react)
  41. * [React Native](#react-native)
  42. * [Rollup](#rollup)
  43. * [PouchDB and CouchDB](#pouchdb-and-couchdb)
  44. * [Mongoose](#mongoose)
  45. * [Web Workers](#web-workers)
  46. * [CLI](#cli)
  47. * [Other Programming Languages](#other-programming-languages)
  48. * [Tools](#tools)
  49. ## Comparison with UUID
  50. Nano ID is quite comparable to UUID v4 (random-based).
  51. It has a similar number of random bits in the ID
  52. (126 in Nano ID and 122 in UUID), so it has a similar collision probability:
  53. > For there to be a one in a billion chance of duplication,
  54. > 103 trillion version 4 IDs must be generated.
  55. There are three main differences between Nano ID and UUID v4:
  56. 1. Nano ID uses a bigger alphabet, so a similar number of random bits
  57. are packed in just 21 symbols instead of 36.
  58. 2. Nano ID code is **4 times less** than `uuid/v4` package:
  59. 130 bytes instead of 483.
  60. 3. Because of memory allocation tricks, Nano ID is **2 times** faster than UUID.
  61. ## Benchmark
  62. ```rust
  63. $ node ./test/benchmark.js
  64. crypto.randomUUID 25,603,857 ops/sec
  65. @napi-rs/uuid 9,973,819 ops/sec
  66. uid/secure 8,234,798 ops/sec
  67. @lukeed/uuid 7,464,706 ops/sec
  68. nanoid 5,616,592 ops/sec
  69. customAlphabet 3,115,207 ops/sec
  70. uuid v4 1,535,753 ops/sec
  71. secure-random-string 388,226 ops/sec
  72. uid-safe.sync 363,489 ops/sec
  73. cuid 187,343 ops/sec
  74. shortid 45,758 ops/sec
  75. Async:
  76. nanoid/async 96,094 ops/sec
  77. async customAlphabet 97,184 ops/sec
  78. async secure-random-string 92,794 ops/sec
  79. uid-safe 90,684 ops/sec
  80. Non-secure:
  81. uid 67,376,692 ops/sec
  82. nanoid/non-secure 2,849,639 ops/sec
  83. rndm 2,674,806 ops/sec
  84. ```
  85. Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 34, Node.js 16.10.
  86. ## Security
  87. *See a good article about random generators theory:
  88. [Secure random values (in Node.js)]*
  89. * **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano ID
  90. uses the `crypto` module in Node.js and the Web Crypto API in browsers.
  91. These modules use unpredictable hardware random generator.
  92. * **Uniformity.** `random % alphabet` is a popular mistake to make when coding
  93. an ID generator. The distribution will not be even; there will be a lower
  94. chance for some symbols to appear compared to others. So, it will reduce
  95. the number of tries when brute-forcing. Nano ID uses a [better algorithm]
  96. and is tested for uniformity.
  97. <img src="img/distribution.png" alt="Nano ID uniformity"
  98. width="340" height="135">
  99. * **Well-documented:** all Nano ID hacks are documented. See comments
  100. in [the source].
  101. * **Vulnerabilities:** to report a security vulnerability, please use
  102. the [Tidelift security contact](https://tidelift.com/security).
  103. Tidelift will coordinate the fix and disclosure.
  104. [Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba
  105. [better algorithm]: https://github.com/ai/nanoid/blob/main/index.js
  106. [the source]: https://github.com/ai/nanoid/blob/main/index.js
  107. ## Install
  108. ```bash
  109. npm install --save nanoid
  110. ```
  111. For quick hacks, you can load Nano ID from CDN. Though, it is not recommended
  112. to be used in production because of the lower loading performance.
  113. ```js
  114. import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
  115. ```
  116. Nano ID provides ES modules. You do not need to do anything to use Nano ID
  117. as ESM in webpack, Rollup, Parcel, or Node.js.
  118. ```js
  119. import { nanoid } from 'nanoid'
  120. ```
  121. In Node.js you can use CommonJS import:
  122. ```js
  123. const { nanoid } = require('nanoid')
  124. ```
  125. ## API
  126. Nano ID has 3 APIs: normal (blocking), asynchronous, and non-secure.
  127. By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID
  128. with 21 characters (to have a collision probability similar to UUID v4).
  129. ### Blocking
  130. The safe and easiest way to use Nano ID.
  131. In rare cases could block CPU from other work while noise collection
  132. for hardware random generator.
  133. ```js
  134. import { nanoid } from 'nanoid'
  135. model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
  136. ```
  137. If you want to reduce the ID size (and increase collisions probability),
  138. you can pass the size as an argument.
  139. ```js
  140. nanoid(10) //=> "IRFa-VaY2b"
  141. ```
  142. Don’t forget to check the safety of your ID size
  143. in our [ID collision probability] calculator.
  144. You can also use a [custom alphabet](#custom-alphabet-or-size)
  145. or a [random generator](#custom-random-bytes-generator).
  146. [ID collision probability]: https://zelark.github.io/nano-id-cc/
  147. ### Async
  148. To generate hardware random bytes, CPU collects electromagnetic noise.
  149. For most cases, entropy will be already collected.
  150. In the synchronous API during the noise collection, the CPU is busy and
  151. cannot do anything useful (for instance, process another HTTP request).
  152. Using the asynchronous API of Nano ID, another code can run during
  153. the entropy collection.
  154. ```js
  155. import { nanoid } from 'nanoid/async'
  156. async function createUser () {
  157. user.id = await nanoid()
  158. }
  159. ```
  160. Read more about entropy collection in [`crypto.randomBytes`] docs.
  161. Unfortunately, you will lose Web Crypto API advantages in a browser
  162. if you use the asynchronous API. So, currently, in the browser, you are limited
  163. with either security (`nanoid`), asynchronous behavior (`nanoid/async`),
  164. or non-secure behavior (`nanoid/non-secure`) that will be explained
  165. in the next part of the documentation.
  166. [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
  167. ### Non-Secure
  168. By default, Nano ID uses hardware random bytes generation for security
  169. and low collision probability. If you are not so concerned with security,
  170. you can use the faster non-secure generator.
  171. ```js
  172. import { nanoid } from 'nanoid/non-secure'
  173. const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
  174. ```
  175. ### Custom Alphabet or Size
  176. `customAlphabet` allows you to create `nanoid` with your own alphabet
  177. and ID size.
  178. ```js
  179. import { customAlphabet } from 'nanoid'
  180. const nanoid = customAlphabet('1234567890abcdef', 10)
  181. model.id = nanoid() //=> "4f90d13a42"
  182. ```
  183. ```js
  184. import { customAlphabet } from 'nanoid/async'
  185. const nanoid = customAlphabet('1234567890abcdef', 10)
  186. async function createUser () {
  187. user.id = await nanoid()
  188. }
  189. ```
  190. ```js
  191. import { customAlphabet } from 'nanoid/non-secure'
  192. const nanoid = customAlphabet('1234567890abcdef', 10)
  193. user.id = nanoid()
  194. ```
  195. Check the safety of your custom alphabet and ID size in our
  196. [ID collision probability] calculator. For more alphabets, check out the options
  197. in [`nanoid-dictionary`].
  198. Alphabet must contain 256 symbols or less.
  199. Otherwise, the security of the internal generator algorithm is not guaranteed.
  200. In addition to setting a default size, you can change the ID size when calling
  201. the function:
  202. ```js
  203. import { customAlphabet } from 'nanoid'
  204. const nanoid = customAlphabet('1234567890abcdef', 10)
  205. model.id = nanoid(5) //=> "f01a2"
  206. ```
  207. [ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/
  208. [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary
  209. ### Custom Random Bytes Generator
  210. `customRandom` allows you to create a `nanoid` and replace alphabet
  211. and the default random bytes generator.
  212. In this example, a seed-based generator is used:
  213. ```js
  214. import { customRandom } from 'nanoid'
  215. const rng = seedrandom(seed)
  216. const nanoid = customRandom('abcdef', 10, size => {
  217. return (new Uint8Array(size)).map(() => 256 * rng())
  218. })
  219. nanoid() //=> "fbaefaadeb"
  220. ```
  221. `random` callback must accept the array size and return an array
  222. with random numbers.
  223. If you want to use the same URL-friendly symbols with `customRandom`,
  224. you can get the default alphabet using the `urlAlphabet`.
  225. ```js
  226. const { customRandom, urlAlphabet } = require('nanoid')
  227. const nanoid = customRandom(urlAlphabet, 10, random)
  228. ```
  229. Asynchronous and non-secure APIs are not available for `customRandom`.
  230. Note, that between Nano ID versions we may change random generator
  231. call sequence. If you are using seed-based generators, we do not guarantee
  232. the same result.
  233. ## Usage
  234. ### IE
  235. If you support IE, you need to [transpile `node_modules`] by Babel
  236. and add `crypto` alias. Moreover, `UInt8Array` in IE actually
  237. is not an array and to cope with it, you have to convert it to an array
  238. manually:
  239. ```js
  240. // polyfills.js
  241. if (!window.crypto && window.msCrypto) {
  242. window.crypto = window.msCrypto
  243. const getRandomValuesDef = window.crypto.getRandomValues
  244. window.crypto.getRandomValues = function (array) {
  245. const values = getRandomValuesDef.call(window.crypto, array)
  246. const result = []
  247. for (let i = 0; i < array.length; i++) {
  248. result[i] = values[i];
  249. }
  250. return result
  251. };
  252. }
  253. ```
  254. ```js
  255. import './polyfills.js'
  256. import { nanoid } from 'nanoid'
  257. ```
  258. [transpile `node_modules`]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
  259. ### React
  260. There’s no correct way to use Nano ID for React `key` prop
  261. since it should be consistent among renders.
  262. ```jsx
  263. function Todos({todos}) {
  264. return (
  265. <ul>
  266. {todos.map(todo => (
  267. <li key={nanoid()}> /* DON’T DO IT */
  268. {todo.text}
  269. </li>
  270. ))}
  271. </ul>
  272. )
  273. }
  274. ```
  275. You should rather try to reach for stable ID inside your list item.
  276. ```jsx
  277. const todoItems = todos.map((todo) =>
  278. <li key={todo.id}>
  279. {todo.text}
  280. </li>
  281. )
  282. ```
  283. In case you don’t have stable IDs you'd rather use index as `key`
  284. instead of `nanoid()`:
  285. ```jsx
  286. const todoItems = todos.map((text, index) =>
  287. <li key={index}> /* Still not recommended but preferred over nanoid().
  288. Only do this if items have no stable IDs. */
  289. {text}
  290. </li>
  291. )
  292. ```
  293. ### React Native
  294. React Native does not have built-in random generator. The following polyfill
  295. works for plain React Native and Expo starting with `39.x`.
  296. 1. Check [`react-native-get-random-values`] docs and install it.
  297. 2. Import it before Nano ID.
  298. ```js
  299. import 'react-native-get-random-values'
  300. import { nanoid } from 'nanoid'
  301. ```
  302. [`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values
  303. ### Rollup
  304. For Rollup you will need [`@rollup/plugin-node-resolve`] to bundle browser version
  305. of this library.:
  306. ```js
  307. plugins: [
  308. nodeResolve({
  309. browser: true
  310. })
  311. ]
  312. ```
  313. [`@rollup/plugin-node-resolve`]: https://github.com/rollup/plugins/tree/master/packages/node-resolve
  314. ### PouchDB and CouchDB
  315. In PouchDB and CouchDB, IDs can’t start with an underscore `_`.
  316. A prefix is required to prevent this issue, as Nano ID might use a `_`
  317. at the start of the ID by default.
  318. Override the default ID with the following option:
  319. ```js
  320. db.put({
  321. _id: 'id' + nanoid(),
  322. })
  323. ```
  324. ### Mongoose
  325. ```js
  326. const mySchema = new Schema({
  327. _id: {
  328. type: String,
  329. default: () => nanoid()
  330. }
  331. })
  332. ```
  333. ### Web Workers
  334. Web Workers do not have access to a secure random generator.
  335. Security is important in IDs when IDs should be unpredictable.
  336. For instance, in "access by URL" link generation.
  337. If you do not need unpredictable IDs, but you need to use Web Workers,
  338. you can use the non‑secure ID generator.
  339. ```js
  340. import { nanoid } from 'nanoid/non-secure'
  341. nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
  342. ```
  343. Note: non-secure IDs are more prone to collision attacks.
  344. ### CLI
  345. You can get unique ID in terminal by calling `npx nanoid`. You need only
  346. Node.js in the system. You do not need Nano ID to be installed anywhere.
  347. ```sh
  348. $ npx nanoid
  349. npx: installed 1 in 0.63s
  350. LZfXLFzPPR4NNrgjlWDxn
  351. ```
  352. Size of generated ID can be specified with `--size` (or `-s`) option:
  353. ```sh
  354. $ npx nanoid --size 10
  355. L3til0JS4z
  356. ```
  357. Custom alphabet can be specified with `--alphabet` (or `-a`) option
  358. (note that in this case `--size` is required):
  359. ```sh
  360. $ npx nanoid --alphabet abc --size 15
  361. bccbcabaabaccab
  362. ```
  363. ### Other Programming Languages
  364. Nano ID was ported to many languages. You can use these ports to have
  365. the same ID generator on the client and server side.
  366. * [C#](https://github.com/codeyu/nanoid-net)
  367. * [C++](https://github.com/mcmikecreations/nanoid_cpp)
  368. * [Clojure and ClojureScript](https://github.com/zelark/nano-id)
  369. * [ColdFusion/CFML](https://github.com/JamoCA/cfml-nanoid)
  370. * [Crystal](https://github.com/mamantoha/nanoid.cr)
  371. * [Dart & Flutter](https://github.com/pd4d10/nanoid-dart)
  372. * [Deno](https://github.com/ianfabs/nanoid)
  373. * [Go](https://github.com/matoous/go-nanoid)
  374. * [Elixir](https://github.com/railsmechanic/nanoid)
  375. * [Haskell](https://github.com/MichelBoucey/NanoID)
  376. * [Janet](https://sr.ht/~statianzo/janet-nanoid/)
  377. * [Java](https://github.com/aventrix/jnanoid)
  378. * [Nim](https://github.com/icyphox/nanoid.nim)
  379. * [OCaml](https://github.com/routineco/ocaml-nanoid)
  380. * [Perl](https://github.com/tkzwtks/Nanoid-perl)
  381. * [PHP](https://github.com/hidehalo/nanoid-php)
  382. * [Python](https://github.com/puyuan/py-nanoid)
  383. with [dictionaries](https://pypi.org/project/nanoid-dictionary)
  384. * [Postgres Extension](https://github.com/spa5k/uids-postgres)
  385. * [R](https://github.com/hrbrmstr/nanoid) (with dictionaries)
  386. * [Ruby](https://github.com/radeno/nanoid.rb)
  387. * [Rust](https://github.com/nikolay-govorov/nanoid)
  388. * [Swift](https://github.com/antiflasher/NanoID)
  389. * [Unison](https://share.unison-lang.org/latest/namespaces/hojberg/nanoid)
  390. * [V](https://github.com/invipal/nanoid)
  391. * [Zig](https://github.com/SasLuca/zig-nanoid)
  392. For other environments, [CLI] is available to generate IDs from a command line.
  393. [CLI]: #cli
  394. ## Tools
  395. * [ID size calculator] shows collision probability when adjusting
  396. the ID alphabet or size.
  397. * [`nanoid-dictionary`] with popular alphabets to use with [`customAlphabet`].
  398. * [`nanoid-good`] to be sure that your ID doesn’t contain any obscene words.
  399. [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary
  400. [ID size calculator]: https://zelark.github.io/nano-id-cc/
  401. [`customAlphabet`]: #custom-alphabet-or-size
  402. [`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good