README.md
This file
Path
README.md
445 lines · 13.3 KiB · Markdown
Last changed by
Document the alphabet bounds instead of guarding them at runtime (#609)Jeff Lenamonbefore adoption8588e3a
History of this fileTake it
The walk stopped after 200 commits: lines older than 51659b4 point at it.
typo in readmeAlexDroomerbefore adoption51659b4
lines 1–5why, one step back1# Nano ID23<img src="https://ai.github.io/nanoid/logo.svg" align="right"4 alt="Nano ID logo by Anton Lovchikov" width="180" height="94">5docs: add Arabic README translation (#556)Mahmoud Hamdybefore adoptiondc629c5
line 6why, one step back6**English** | [日本語](./README.ja.md) | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) | [한국어](./README.ko.md) | [العربية](./README.ar.md)typo in readmeAlexDroomerbefore adoption51659b4
lines 7–12why, one step back78A tiny, secure, URL-friendly, unique string ID generator for JavaScript.910> “An amazing level of senseless perfectionism,11> which is simply impossible not to respect.”12Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 13why, one step back13- **Small.** 118 bytes (minified and brotlied). No dependencies.typo in readmeAlexDroomerbefore adoption51659b4
line 14why, one step back14 [Size Limit] controls the size.Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f
line 15why, one step back15- **Fast.** 50% faster than native `crypto.randomUUID()`.Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 16–17why, one step back16- **Safe.** It uses hardware random generator. Can be used in clusters.17- **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).typo in readmeAlexDroomerbefore adoption51659b4
line 18why, one step back18 So ID size was reduced from 36 to 21 symbols.Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 19why, one step back19- **Portable.** Nano ID was portedtypo in readmeAlexDroomerbefore adoption51659b4
lines 20–28why, one step back20 to over [20 programming languages](./README.md#other-programming-languages).2122```js23import { nanoid } from 'nanoid'24model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"25```2627---28Update EM bannerAndrey Sitnikbefore adoptionb49a237
line 29why, one step back29<img src="https://cdn.evilmartians.com/badges/logo-no-label.svg" alt="" width="22" height="16" /> Nano ID is built by <b><a href="https://evilmartians.com/">Evil Martians</a></b>, an American design and engineering consultancy for <b>developer tools, AI, and cybersecurity startups</b>.typo in readmeAlexDroomerbefore adoption51659b4
lines 30–32why, one step back3031---32Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 33why, one step back33[Size Limit]: https://github.com/ai/size-limittypo in readmeAlexDroomerbefore adoption51659b4
lines 34–41why, one step back3435## Table of Contents3637- [Table of Contents](#table-of-contents)38- [Comparison with UUID](#comparison-with-uuid)39- [Benchmark](#benchmark)40- [Security](#security)41- [Install](#install)Add JSR docsAndrey Sitnikbefore adoption6ed8f57
line 42why, one step back42 - [JSR](#jsr)Clean up docsAndrey Sitnikbefore adoption90bb934
line 43why, one step back43 - [CDN](#cdn)typo in readmeAlexDroomerbefore adoption51659b4
lines 44–46why, one step back44- [API](#api)45 - [Custom Alphabet or Size](#custom-alphabet-or-size)46 - [Custom Random Bytes Generator](#custom-random-bytes-generator)Update docsAndrey Sitnikbefore adoptionc0779bd
line 47why, one step back47 - [Non-Secure](#non-secure)typo in readmeAlexDroomerbefore adoption51659b4
lines 48–52why, one step back48- [Usage](#usage)49 - [React](#react)50 - [React Native](#react-native)51 - [PouchDB and CouchDB](#pouchdb-and-couchdb)52 - [CLI](#cli)Clean up docsAndrey Sitnikbefore adoptionf7862cb
line 53why, one step back53 - [TypeScript](#typescript)typo in readmeAlexDroomerbefore adoption51659b4
lines 54–69why, one step back54 - [Other Programming Languages](#other-programming-languages)55- [Tools](#tools)5657## Comparison with UUID5859Nano ID is quite comparable to UUID v4 (random-based).60It has a similar number of random bits in the ID61(126 in Nano ID and 122 in UUID), so it has a similar collision probability:6263> For there to be a one in a billion chance of duplication,64> 103 trillion version 4 IDs must be generated.6566There are two main differences between Nano ID and UUID v4:67681. Nano ID uses a bigger alphabet, so a similar number of random bits69 are packed in just 21 symbols instead of 36.Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f
line 70why, one step back702. Nano ID is faster than `crypto.randomUUID` and `uuid/v4`.typo in readmeAlexDroomerbefore adoption51659b4
lines 71–75why, one step back7172## Benchmark7374```rust75$ node ./test/benchmark.jsPort amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f
lines 76–86why, one step back76nope-id 20,386,830 ops/sec77nanoid 20,434,827 ops/sec78customAlphabet 20,544,476 ops/sec79crypto.randomUUID 12,865,759 ops/sec80uuid v4 7,930,104 ops/sec81@napi-rs/uuid 5,573,171 ops/sec82uid/secure 6,308,267 ops/sec83@lukeed/uuid 5,278,597 ops/sec84nanoid for browser 311,497 ops/sec85secure-random-string 301,667 ops/sec86uid-safe.sync 297,815 ops/sectypo in readmeAlexDroomerbefore adoption51659b4
lines 87–88why, one step back8788Non-secure:Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f
lines 89–91why, one step back89uid 20,286,757 ops/sec90nanoid/non-secure 2,397,594 ops/sec91rndm 2,445,462 ops/sectypo in readmeAlexDroomerbefore adoption51659b4
lines 92–95why, one step back92```9394## Security95Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 96–97why, one step back96_See a good article about random generators theory:97[Secure random values (in Node.js)]_typo in readmeAlexDroomerbefore adoption51659b4
line 98why, one step back98Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 99why, one step back99- **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano IDtypo in readmeAlexDroomerbefore adoption51659b4
lines 100–101why, one step back100 uses the `crypto` module in Node.js and the Web Crypto API in browsers.101 These modules use unpredictable hardware random generator.Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 102why, one step back102- **Uniformity.** `random % alphabet` is a popular mistake to make when codingtypo in readmeAlexDroomerbefore adoption51659b4
lines 103–110why, one step back103 an ID generator. The distribution will not be even; there will be a lower104 chance for some symbols to appear compared to others. So, it will reduce105 the number of tries when brute-forcing. Nano ID uses a [better algorithm]106 and is tested for uniformity.107108 <img src="img/distribution.png" alt="Nano ID uniformity"109 width="340" height="135">110Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 111why, one step back111- **Well-documented:** all Nano ID hacks are documented. See commentstypo in readmeAlexDroomerbefore adoption51659b4
line 112why, one step back112 in [the source].Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 113why, one step back113- **Vulnerabilities:** to report a security vulnerability, please usetypo in readmeAlexDroomerbefore adoption51659b4
lines 114–117why, one step back114 the [Tidelift security contact](https://tidelift.com/security).115 Tidelift will coordinate the fix and disclosure.116117[Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfbaMove from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 118–119why, one step back118[better algorithm]: https://github.com/ai/nanoid/blob/main/index.js119[the source]: https://github.com/ai/nanoid/blob/main/index.jstypo in readmeAlexDroomerbefore adoption51659b4
lines 120–122why, one step back120121## Install122Clean up docsAndrey Sitnikbefore adoption90bb934
lines 123–124why, one step back123```bash124npm install nanoidtypo in readmeAlexDroomerbefore adoption51659b4
lines 125–126why, one step back125```126Add JSR docsAndrey Sitnikbefore adoption6ed8f57
lines 127–145why, one step back127### JSR128129[JSR](https://jsr.io) is a replacement for npm with open governance130and active development (in contrast to npm).131132```bash133npx jsr add @sitnik/nanoid134```135136You can use it in Node.js, Deno, Bun, etc.137138```js139// Replace `nanoid` to `@sitnik/nanoid` in all imports140import { nanoid } from '@sitnik/nanoid'141```142143For Deno install it by `deno add jsr:@sitnik/nanoid` or import144from `jsr:@sitnik/nanoid`.145Clean up docsAndrey Sitnikbefore adoption90bb934
lines 146–153why, one step back146### CDN147148For quick hacks, you can load Nano ID from CDN. Though, it is not recommended149to be used in production because of the lower loading performance.150151```js152import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'153```typo in readmeAlexDroomerbefore adoption51659b4
lines 154–200why, one step back154155## API156157By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID158with 21 characters (to have a collision probability similar to UUID v4).159160```js161import { nanoid } from 'nanoid'162model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"163```164165If you want to reduce the ID size (and increase collisions probability),166you can pass the size as an argument.167168```js169nanoid(10) //=> "IRFa-VaY2b"170```171172Don’t forget to check the safety of your ID size173in our [ID collision probability] calculator.174175You can also use a [custom alphabet](#custom-alphabet-or-size)176or a [random generator](#custom-random-bytes-generator).177178[ID collision probability]: https://zelark.github.io/nano-id-cc/179180### Custom Alphabet or Size181182`customAlphabet` returns a function that allows you to create `nanoid`183with your own alphabet and ID size.184185```js186import { customAlphabet } from 'nanoid'187const nanoid = customAlphabet('1234567890abcdef', 10)188model.id = nanoid() //=> "4f90d13a42"189```190191```js192import { customAlphabet } from 'nanoid/non-secure'193const nanoid = customAlphabet('1234567890abcdef', 10)194user.id = nanoid()195```196197Check the safety of your custom alphabet and ID size in our198[ID collision probability] calculator. For more alphabets, check out the options199in [`nanoid-dictionary`].200Document the alphabet bounds instead of guarding them at runtime (#609)Jeff Lenamonbefore adoption8588e3a
lines 201–204why, one step back201Alphabet must contain from 1 to 256 symbols.202Otherwise, the security of the internal generator algorithm is not guaranteed,203and a generator built from an empty or over-256-symbol alphabet204can loop forever instead of returning an ID.typo in readmeAlexDroomerbefore adoption51659b4
lines 205–214why, one step back205206In addition to setting a default size, you can change the ID size when calling207the function:208209```js210import { customAlphabet } from 'nanoid'211const nanoid = customAlphabet('1234567890abcdef', 10)212model.id = nanoid(5) //=> "f01a2"213```214Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 215why, one step back215[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionarytypo in readmeAlexDroomerbefore adoption51659b4
lines 216–228why, one step back216217### Custom Random Bytes Generator218219`customRandom` allows you to create a `nanoid` and replace alphabet220and the default random bytes generator.221222In this example, a seed-based generator is used:223224```js225import { customRandom } from 'nanoid'226227const rng = seedrandom(seed)228const nanoid = customRandom('abcdef', 10, size => {Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 229why, one step back229 return new Uint8Array(size).map(() => 256 * rng())typo in readmeAlexDroomerbefore adoption51659b4
lines 230–241why, one step back230})231232nanoid() //=> "fbaefaadeb"233```234235`random` callback must accept the array size and return an array236with random numbers.237238If you want to use the same URL-friendly symbols with `customRandom`,239you can get the default alphabet using the `urlAlphabet`.240241```jsFix outdated info and links in README (#566)Mahmoud Hamdybefore adoptionc7ca9e9
line 242why, one step back242import { customRandom, urlAlphabet } from 'nanoid'typo in readmeAlexDroomerbefore adoption51659b4
lines 243–248why, one step back243const nanoid = customRandom(urlAlphabet, 10, random)244```245246Note, that between Nano ID versions we may change random generator247call sequence. If you are using seed-based generators, we do not guarantee248the same result.Update docsAndrey Sitnikbefore adoptionc0779bd
lines 249–262why, one step back249250### Non-Secure251252Nano ID uses hardware random bytes generation for security and low collision253probability. If you are not so concerned with security, you can use it254for environments without hardware random generators.255256```js257import { nanoid } from 'nanoid/non-secure'258const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"259```260261Note, that non-secure version is _slower_ than secure.262Use it only if you have to.typo in readmeAlexDroomerbefore adoption51659b4
lines 263–271why, one step back263264## Usage265266### React267268There’s no correct way to use Nano ID for React `key` prop269since it should be consistent among renders.270271```jsxMove from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 272why, one step back272function Todos({ todos }) {typo in readmeAlexDroomerbefore adoption51659b4
lines 273–275why, one step back273 return (274 <ul>275 {todos.map(todo => (Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 276–278why, one step back276 <li key={nanoid()}>277 {' '}278 /* DON’T DO IT */typo in readmeAlexDroomerbefore adoption51659b4
lines 279–289why, one step back279 {todo.text}280 </li>281 ))}282 </ul>283 )284}285```286287You should rather try to reach for stable ID inside your list item.288289```jsxMove from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 290why, one step back290const todoItems = todos.map(todo => <li key={todo.id}>{todo.text}</li>)typo in readmeAlexDroomerbefore adoption51659b4
lines 291–296why, one step back291```292293In case you don’t have stable IDs you'd rather use index as `key`294instead of `nanoid()`:295296```jsxMove from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 297–301why, one step back297const todoItems = todos.map((text, index) => (298 <li key={index}>299 {' '}300 /* Still not recommended but preferred over nanoid(). Only do this if items301 have no stable IDs. */typo in readmeAlexDroomerbefore adoption51659b4
lines 302–303why, one step back302 {text}303 </li>Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 304why, one step back304))typo in readmeAlexDroomerbefore adoption51659b4
lines 305–310why, one step back305```306307In case you just need random IDs to link elements like labels308and input fields together, [`useId`] is recommended.309That hook was added in React 18.310Fix outdated info and links in README (#566)Mahmoud Hamdybefore adoptionc7ca9e9
line 311why, one step back311[`useId`]: https://react.dev/reference/react/useIdtypo in readmeAlexDroomerbefore adoption51659b4
lines 312–368why, one step back312313### React Native314315React Native does not have built-in random generator. The following polyfill316works for plain React Native and Expo starting with `39.x`.3173181. Check [`react-native-get-random-values`] docs and install it.3192. Import it before Nano ID.320321```js322import 'react-native-get-random-values'323import { nanoid } from 'nanoid'324```325326[`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values327328### PouchDB and CouchDB329330In PouchDB and CouchDB, IDs can’t start with an underscore `_`.331A prefix is required to prevent this issue, as Nano ID might use a `_`332at the start of the ID by default.333334Override the default ID with the following option:335336```js337db.put({338 _id: 'id' + nanoid(),339 …340})341```342343### CLI344345You can get unique ID in terminal by calling `npx nanoid`. You need only346Node.js in the system. You do not need Nano ID to be installed anywhere.347348```sh349$ npx nanoid350npx: installed 1 in 0.63s351LZfXLFzPPR4NNrgjlWDxn352```353354Size of generated ID can be specified with `--size` (or `-s`) option:355356```sh357$ npx nanoid --size 10358L3til0JS4z359```360361Custom alphabet can be specified with `--alphabet` (or `-a`) option362(note that in this case `--size` is required):363364```sh365$ npx nanoid --alphabet abc --size 15366bccbcabaabaccab367```368Make functions generic so it can cast to opaque (branded) types (#521)Sasha Kossbefore adoptionea64dc7
lines 369–375why, one step back369### TypeScript370371Nano ID allows casting generated strings into opaque strings in TypeScript.372For example:373374```ts375declare const userIdBrand: unique symbolClean up docsAndrey Sitnikbefore adoptionf7862cb
line 376why, one step back376type UserId = string & { [userIdBrand]: true }Make functions generic so it can cast to opaque (branded) types (#521)Sasha Kossbefore adoptionea64dc7
line 377why, one step back377Clean up docsAndrey Sitnikbefore adoptionf7862cb
lines 378–380why, one step back378// Use explicit type parameter:379mockUser(nanoid<UserId>())380Make functions generic so it can cast to opaque (branded) types (#521)Sasha Kossbefore adoptionea64dc7
lines 381–391why, one step back381interface User {382 id: UserId383 name: string384}385386const user: User = {387 // Automatically casts to UserId:388 id: nanoid(),389 name: 'Alice'390}391```typo in readmeAlexDroomerbefore adoption51659b4
lines 392–397why, one step back392393### Other Programming Languages394395Nano ID was ported to many languages. You can use these ports to have396the same ID generator on the client and server side.397Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 398–418why, one step back398- [C](https://github.com/lukateras/nanoid.h)399- [C#](https://github.com/codeyu/nanoid-net)400- [C++](https://github.com/mcmikecreations/nanoid_cpp)401- [Clojure and ClojureScript](https://github.com/zelark/nano-id)402- [ColdFusion/CFML](https://github.com/JamoCA/cfml-nanoid)403- [Crystal](https://github.com/mamantoha/nanoid.cr)404- [Dart & Flutter](https://github.com/pd4d10/nanoid-dart)405- [Elixir](https://github.com/railsmechanic/nanoid)406- [Gleam](https://github.com/0xca551e/glanoid)407- [Go](https://github.com/matoous/go-nanoid)408- [Haskell](https://github.com/MichelBoucey/NanoID)409- [Haxe](https://github.com/flashultra/uuid)410- [Janet](https://sr.ht/~statianzo/janet-nanoid/)411- [Java](https://github.com/wosherco/jnanoid-enhanced)412- [Kotlin](https://github.com/viascom/nanoid-kotlin)413- [MySQL/MariaDB](https://github.com/viascom/nanoid-mysql-mariadb)414- [Nim](https://github.com/icyphox/nanoid.nim)415- [OCaml](https://github.com/routineco/ocaml-nanoid)416- [Perl](https://github.com/tkzwtks/Nanoid-perl)417- [PHP](https://github.com/hidehalo/nanoid-php)418- Python [native](https://github.com/puyuan/py-nanoid) implementationtypo in readmeAlexDroomerbefore adoption51659b4
lines 419–420why, one step back419 with [dictionaries](https://pypi.org/project/nanoid-dictionary)420 and [fast](https://github.com/oliverlambson/fastnanoid) implementation (written in Rust)Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 421why, one step back421- Postgres [Extension](https://github.com/spa5k/uids-postgres)typo in readmeAlexDroomerbefore adoption51659b4
line 422why, one step back422 and [Native Function](https://github.com/viascom/nanoid-postgres)Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 423–429why, one step back423- [R](https://github.com/hrbrmstr/nanoid) (with dictionaries)424- [Ruby](https://github.com/radeno/nanoid.rb)425- [Rust](https://github.com/nikolay-govorov/nanoid)426- [Swift](https://github.com/ShivaHuang/swift-nanoid)427- [Unison](https://share.unison-lang.org/latest/namespaces/hojberg/nanoid)428- [V](https://github.com/invipal/nanoid)429- [Zig](https://github.com/SasLuca/zig-nanoid)typo in readmeAlexDroomerbefore adoption51659b4
lines 430–436why, one step back430431For other environments, [CLI] is available to generate IDs from a command line.432433[CLI]: #cli434435## Tools436Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
line 437why, one step back437- [ID size calculator] shows collision probability when adjustingtypo in readmeAlexDroomerbefore adoption51659b4
line 438why, one step back438 the ID alphabet or size.Move from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 439–440why, one step back439- [`nanoid-dictionary`] with popular alphabets to use with [`customAlphabet`].440- [`nanoid-good`] to be sure that your ID doesn’t contain any obscene words.typo in readmeAlexDroomerbefore adoption51659b4
lines 441–442why, one step back441442[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionaryMove from Prettier and ESLint to oxfmt and oxlintAndrey Sitnikbefore adoption4bf7b85
lines 443–445why, one step back443[ID size calculator]: https://zelark.github.io/nano-id-cc/444[`customAlphabet`]: #custom-alphabet-or-size445[`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good