Skip to content
Myr

README.md

This file

Path

README.md

425 lines · 12.9 KiB · Markdown

Last changed by

landed by oscabrielc0d01e3

History of this file

Take it

Show it rendered

1# 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">56**English** | [日本語](./README.ja.md) | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) | [한국어](./README.ko.md) | [العربية](./README.ar.md)78A 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.”1213- **Small.** 117 bytes (minified and brotlied). No dependencies.14  [Size Limit] controls the size.15- **Fast.** 50% faster than native `crypto.randomUUID()`.16- **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_-`).18  So ID size was reduced from 36 to 21 symbols.19- **Portable.** Nano ID was ported20  to over [20 programming languages](./README.md#other-programming-languages).2122```js23import { nanoid } from "nanoid";24model.id = nanoid(); //=> "V1StGXR8_Z5jdHi6B-myT"25```2627---2829<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>.3031---3233[Size Limit]: https://github.com/ai/size-limit3435## 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)42  - [CDN](#cdn)43- [API](#api)44  - [Custom Alphabet or Size](#custom-alphabet-or-size)45  - [Custom Random Bytes Generator](#custom-random-bytes-generator)46  - [Non-Secure](#non-secure)47- [Usage](#usage)48  - [React](#react)49  - [React Native](#react-native)50  - [PouchDB and CouchDB](#pouchdb-and-couchdb)51  - [CLI](#cli)52  - [TypeScript](#typescript)53  - [Other Programming Languages](#other-programming-languages)54- [Tools](#tools)5556## Comparison with UUID5758Nano ID is quite comparable to UUID v4 (random-based).59It has a similar number of random bits in the ID60(126 in Nano ID and 122 in UUID), so it has a similar collision probability:6162> For there to be a one in a billion chance of duplication,63> 103 trillion version 4 IDs must be generated.6465There are two main differences between Nano ID and UUID v4:66671. Nano ID uses a bigger alphabet, so a similar number of random bits68   are packed in just 21 symbols instead of 36.692. Nano ID is faster than `crypto.randomUUID` and `uuid/v4`.7071## Benchmark7273```rust74$ node ./test/benchmark.js75nope-id                 20,386,830 ops/sec76nanoid                  20,434,827 ops/sec77customAlphabet          20,544,476 ops/sec78crypto.randomUUID       12,865,759 ops/sec79uuid v4                  7,930,104 ops/sec80@napi-rs/uuid            5,573,171 ops/sec81uid/secure               6,308,267 ops/sec82@lukeed/uuid             5,278,597 ops/sec83nanoid for browser         311,497 ops/sec84secure-random-string       301,667 ops/sec85uid-safe.sync              297,815 ops/sec8687Non-secure:88uid                     20,286,757 ops/sec89nanoid/non-secure        2,397,594 ops/sec90rndm                     2,445,462 ops/sec91```9293## Security9495_See a good article about random generators theory:96[Secure random values (in Node.js)]_9798- **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano ID99  uses the `crypto` module in Node.js and the Web Crypto API in browsers.100  These modules use unpredictable hardware random generator.101- **Uniformity.** `random % alphabet` is a popular mistake to make when coding102  an ID generator. The distribution will not be even; there will be a lower103  chance for some symbols to appear compared to others. So, it will reduce104  the number of tries when brute-forcing. Nano ID uses a [better algorithm]105  and is tested for uniformity.106107  <img src="img/distribution.png" alt="Nano ID uniformity"108     width="340" height="135">109110- **Well-documented:** all Nano ID hacks are documented. See comments111  in [the source].112- **Vulnerabilities:** to report a security vulnerability, please use113  the [Tidelift security contact](https://tidelift.com/security).114  Tidelift will coordinate the fix and disclosure.115116[Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba117[better algorithm]: https://github.com/ai/nanoid/blob/main/index.js118[the source]: https://github.com/ai/nanoid/blob/main/index.js119120## Install121122```bash123npm install nanoid124```125126### CDN127128For quick hacks, you can load Nano ID from CDN. Though, it is not recommended129to be used in production because of the lower loading performance.130131```js132import { nanoid } from "https://cdn.jsdelivr.net/npm/nanoid/nanoid.js";133```134135## API136137By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID138with 21 characters (to have a collision probability similar to UUID v4).139140```js141import { nanoid } from "nanoid";142model.id = nanoid(); //=> "V1StGXR8_Z5jdHi6B-myT"143```144145If you want to reduce the ID size (and increase collisions probability),146you can pass the size as an argument.147148```js149nanoid(10); //=> "IRFa-VaY2b"150```151152Don’t forget to check the safety of your ID size153in our [ID collision probability] calculator.154155You can also use a [custom alphabet](#custom-alphabet-or-size)156or a [random generator](#custom-random-bytes-generator).157158[ID collision probability]: https://zelark.github.io/nano-id-cc/159160### Custom Alphabet or Size161162`customAlphabet` returns a function that allows you to create `nanoid`163with your own alphabet and ID size.164165```js166import { customAlphabet } from "nanoid";167const nanoid = customAlphabet("1234567890abcdef", 10);168model.id = nanoid(); //=> "4f90d13a42"169```170171```js172import { customAlphabet } from "nanoid/non-secure";173const nanoid = customAlphabet("1234567890abcdef", 10);174user.id = nanoid();175```176177Check the safety of your custom alphabet and ID size in our178[ID collision probability] calculator. For more alphabets, check out the options179in [`nanoid-dictionary`].180181Alphabet must contain from 1 to 256 symbols.182Otherwise, the security of the internal generator algorithm is not guaranteed,183and a generator built from an empty or over-256-symbol alphabet184can loop forever instead of returning an ID.185186In addition to setting a default size, you can change the ID size when calling187the function:188189```js190import { customAlphabet } from "nanoid";191const nanoid = customAlphabet("1234567890abcdef", 10);192model.id = nanoid(5); //=> "f01a2"193```194195[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary196197### Custom Random Bytes Generator198199`customRandom` allows you to create a `nanoid` and replace alphabet200and the default random bytes generator.201202In this example, a seed-based generator is used:203204```js205import { customRandom } from "nanoid";206207const rng = seedrandom(seed);208const nanoid = customRandom("abcdef", 10, (size) => {209  return new Uint8Array(size).map(() => 256 * rng());210});211212nanoid(); //=> "fbaefaadeb"213```214215`random` callback must accept the array size and return an array216with random numbers.217218If you want to use the same URL-friendly symbols with `customRandom`,219you can get the default alphabet using the `urlAlphabet`.220221```js222import { customRandom, urlAlphabet } from "nanoid";223const nanoid = customRandom(urlAlphabet, 10, random);224```225226Note, that between Nano ID versions we may change random generator227call sequence. If you are using seed-based generators, we do not guarantee228the same result.229230### Non-Secure231232Nano ID uses hardware random bytes generation for security and low collision233probability. If you are not so concerned with security, you can use it234for environments without hardware random generators.235236```js237import { nanoid } from "nanoid/non-secure";238const id = nanoid(); //=> "Uakgb_J5m9g-0JDMbcJqLJ"239```240241Note, that non-secure version is _slower_ than secure.242Use it only if you have to.243244## Usage245246### React247248There’s no correct way to use Nano ID for React `key` prop249since it should be consistent among renders.250251```jsx252function Todos({ todos }) {253  return (254    <ul>255      {todos.map((todo) => (256        <li key={nanoid()}>257          {" "}258          /* DON’T DO IT */259          {todo.text}260        </li>261      ))}262    </ul>263  );264}265```266267You should rather try to reach for stable ID inside your list item.268269```jsx270const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);271```272273In case you don’t have stable IDs you'd rather use index as `key`274instead of `nanoid()`:275276```jsx277const todoItems = todos.map((text, index) => (278  <li key={index}>279    {" "}280    /* Still not recommended but preferred over nanoid(). Only do this if items have no stable IDs.281    */282    {text}283  </li>284));285```286287In case you just need random IDs to link elements like labels288and input fields together, [`useId`] is recommended.289That hook was added in React 18.290291[`useId`]: https://react.dev/reference/react/useId292293### React Native294295React Native does not have built-in random generator. The following polyfill296works for plain React Native and Expo starting with `39.x`.2972981. Check [`react-native-get-random-values`] docs and install it.2992. Import it before Nano ID.300301```js302import "react-native-get-random-values";303import { nanoid } from "nanoid";304```305306[`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values307308### PouchDB and CouchDB309310In PouchDB and CouchDB, IDs can’t start with an underscore `_`.311A prefix is required to prevent this issue, as Nano ID might use a `_`312at the start of the ID by default.313314Override the default ID with the following option:315316```js317db.put({318  _id: 'id' + nanoid(),319  …320})321```322323### CLI324325You can get unique ID in terminal by calling `npx nanoid`. You need only326Node.js in the system. You do not need Nano ID to be installed anywhere.327328```sh329$ npx nanoid330npx: installed 1 in 0.63s331LZfXLFzPPR4NNrgjlWDxn332```333334Size of generated ID can be specified with `--size` (or `-s`) option:335336```sh337$ npx nanoid --size 10338L3til0JS4z339```340341Custom alphabet can be specified with `--alphabet` (or `-a`) option342(note that in this case `--size` is required):343344```sh345$ npx nanoid --alphabet abc --size 15346bccbcabaabaccab347```348349### TypeScript350351Nano ID allows casting generated strings into opaque strings in TypeScript.352For example:353354```ts355declare const userIdBrand: unique symbol;356type UserId = string & { [userIdBrand]: true };357358// Use explicit type parameter:359mockUser(nanoid<UserId>());360361interface User {362  id: UserId;363  name: string;364}365366const user: User = {367  // Automatically casts to UserId:368  id: nanoid(),369  name: "Alice",370};371```372373### Other Programming Languages374375Nano ID was ported to many languages. You can use these ports to have376the same ID generator on the client and server side.377378- [C](https://github.com/lukateras/nanoid.h)379- [C#](https://github.com/codeyu/nanoid-net)380- [C++](https://github.com/mcmikecreations/nanoid_cpp)381- [Clojure and ClojureScript](https://github.com/zelark/nano-id)382- [ColdFusion/CFML](https://github.com/JamoCA/cfml-nanoid)383- [Crystal](https://github.com/mamantoha/nanoid.cr)384- [Dart & Flutter](https://github.com/pd4d10/nanoid-dart)385- [Elixir](https://github.com/railsmechanic/nanoid)386- [Gleam](https://github.com/0xca551e/glanoid)387- [Go](https://github.com/matoous/go-nanoid)388- [Haskell](https://github.com/MichelBoucey/NanoID)389- [Haxe](https://github.com/flashultra/uuid)390- [Janet](https://sr.ht/~statianzo/janet-nanoid/)391- [Java](https://github.com/wosherco/jnanoid-enhanced)392- [Kotlin](https://github.com/viascom/nanoid-kotlin)393- [MySQL/MariaDB](https://github.com/viascom/nanoid-mysql-mariadb)394- [Nim](https://github.com/icyphox/nanoid.nim)395- [OCaml](https://github.com/routineco/ocaml-nanoid)396- [Perl](https://github.com/tkzwtks/Nanoid-perl)397- [PHP](https://github.com/hidehalo/nanoid-php)398- Python [native](https://github.com/puyuan/py-nanoid) implementation399  with [dictionaries](https://pypi.org/project/nanoid-dictionary)400  and [fast](https://github.com/oliverlambson/fastnanoid) implementation (written in Rust)401- Postgres [Extension](https://github.com/spa5k/uids-postgres)402  and [Native Function](https://github.com/viascom/nanoid-postgres)403- [R](https://github.com/hrbrmstr/nanoid) (with dictionaries)404- [Ruby](https://github.com/radeno/nanoid.rb)405- [Rust](https://github.com/nikolay-govorov/nanoid)406- [Swift](https://github.com/ShivaHuang/swift-nanoid)407- [Unison](https://share.unison-lang.org/latest/namespaces/hojberg/nanoid)408- [V](https://github.com/invipal/nanoid)409- [Zig](https://github.com/SasLuca/zig-nanoid)410411For other environments, [CLI] is available to generate IDs from a command line.412413[CLI]: #cli414415## Tools416417- [ID size calculator] shows collision probability when adjusting418  the ID alphabet or size.419- [`nanoid-dictionary`] with popular alphabets to use with [`customAlphabet`].420- [`nanoid-good`] to be sure that your ID doesn’t contain any obscene words.421422[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary423[ID size calculator]: https://zelark.github.io/nano-id-cc/424[`customAlphabet`]: #custom-alphabet-or-size425[`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good