A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
- Small. 110 bytes (minified and gzipped). No dependencies. Size Limit controls the size.
- Safe. It uses cryptographically strong random APIs. Can be used in clusters.
- Fast. It’s 16% faster than UUID.
- Compact. It uses a larger alphabet than UUID (
A-Za-z0-9_-
). So ID size was reduced from 36 to 21 symbols.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Supports modern browsers, IE with Babel, Node.js and React Native.
Try to make us smaller in online tool.
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:
- Nano ID uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.
- Nano ID code is 3 times less than
uuid/v4
package: 110 bytes instead of 345. - Because of memory allocation tricks, Nano ID is 16% faster than UUID.
$ ./test/benchmark
nanoid 693,132 ops/sec
nanoid/generate 624,291 ops/sec
uid.sync 487,706 ops/sec
uuid/v4 471,299 ops/sec
secure-random-string 448,386 ops/sec
shortid 66,809 ops/sec
Async:
nanoid/async 105,024 ops/sec
nanoid/async/generate 106,682 ops/sec
secure-random-string 94,217 ops/sec
uid 92,026 ops/sec
Non-secure:
nanoid/non-secure 2,555,814 ops/sec
rndm 2,413,565 ops/sec
- ID size calculator to choice smaller ID size depends on your case.
nanoid-dictionary
with popular alphabets to use withnanoid/generate
.nanoid-cli
to generate ID from CLI.nanoid-good
to be sure that your ID doesn't contain any obscene words.
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 thecrypto
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 spread 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. -
Vulnerabilities: to report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
The main module uses URL-friendly symbols (A-Za-z0-9_-
) and returns an ID
with 21 characters (to have a collision probability similar to UUID v4).
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
If you want to reduce ID length (and increase collisions probability), you can pass the length as an argument.
nanoid(10) //=> "IRFa-VaY2b"
Don’t forget to check the safety of your ID length in our ID collision probability calculator.
You can also use custom alphabet or random generator.
Do not use a nanoid for key
prop. In React key
should be consistence
between renders. This is bad code:
<Item key={nanoid()} /> /* DON’T DO IT */
This is good code. id
will be generated only once:
const Element = () => {
const [id] = React.useState(nanoid)
return <Item key={id}>
}
If you want to use Nano ID for id
, you must to set some string prefix.
Nano ID could be started from number. HTML ID can’t be started from the number.
<input id={'id' + this.id} type="text"/>
React Native doesn’t have built-in random generator.
- Check
react-native-get-random-values
docs and install it. - Import it before Nano ID.
import 'react-native-get-random-values'
import { nanoid } from 'nanoid'
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:
db.put({
_id: 'id' + nanoid(),
…
})
const mySchema = new Schema({
_id: {
type: String,
default: () => nanoid()
}
})
Nano ID provides ES modules out of the box. You do not need to do anything to use Nano ID as ES module in Webpack, Parcel, or Node.js.
import { nanoid } from 'nanoid'
For quick hacks you can load Nano ID from CDN. We have special minified
nanoid.js
module. Do not use it in production because of low performance.
import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
Web Workers don’t 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 don’t need unpredictable IDs, but you need Web Workers support, you can use non‑secure ID generator. Note, that they have bigger collision probability.
import { nanoid } from 'nanoid/non-secure'
nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Nano ID was ported to many languages. You can use these ports to have the same ID generators on client and server side.
- C#
- Clojure and ClojureScript
- Crystal
- Dart
- Go
- Elixir
- Haskell
- Java
- Nim
- PHP
- Python with dictionaries
- Ruby
- Rust
- Swift
Also, CLI tool is available to generate IDs from a command line.
To generate hardware random bytes, CPU will collect electromagnetic noise. During the collection, CPU doesn’t work.
If we will use asynchronous API for random generator, another code could be executed during the entropy collection.
import { nanoid } from 'nanoid/async'
async function createUser () {
user.id = await nanoid()
}
Unfortunately, you will not have any benefits in a browser, since Web Crypto API doesn’t have asynchronous API.
By default, Nano ID uses hardware random generator for security and low collision probability. If you don’t need it, you can use very fast non-secure generator.
import { nanoid } from 'nanoid/non-secure'
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Note that it is predictable and have bigger collision probability.
customAlphabet
allows you to create nanoid
with own alphabet and ID length.
import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid() //=> "4f90d13a42"
Check the safety of your custom alphabet and ID length
in our ID collision probability calculator.
You can find popular alphabets in nanoid-dictionary
.
Alphabet must contain 256 symbols or less. Otherwise, the generator will not be secure.
Asynchronous and non-secure API is also available:
import { customAlphabet } from 'nanoid/async'
const nanoid = customAlphabet('1234567890abcdef', 10)
async function createUser () {
user.id = await nanoid()
}
import { customAlphabet } from 'nanoid/non-secure'
const nanoid = customAlphabet('1234567890abcdef', 10)
user.id = nanoid()
customRandom
allows you to create nanoid
and replace the default
safe random generator. For instance, to use a seed-based generator.
import { customRandom } from 'nanoid'
function random (size) {
const result = []
for (let i = 0; i < size; i++) {
result.push(randomByte())
}
return result
}
const nanoid = customRandom('abcdef', 10, random)
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 nanoid3
,
you can get the default alphabet from the urlAlphabet
.
const { customRandom, urlAlphabet } = require('nanoid')
const nanoid = customRandom(urlAlphabet, 10, random)
Asynchronous and non-secure APIs are not available for customRandom
.