nanoid
A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
Top Related Projects
Quick Overview
Nanoid is a tiny, secure, URL-friendly, unique string ID generator for JavaScript. It's designed to create compact, collision-resistant identifiers that are suitable for use in URLs and databases. Nanoid is significantly smaller in size compared to UUID, while still maintaining a high degree of uniqueness.
Pros
- Extremely small size (130 bytes minified and gzipped)
- Generates URL-friendly IDs (uses A-Za-z0-9_- characters)
- Highly customizable (length, alphabet, and random number generator)
- Available for multiple programming languages
Cons
- Not as widely adopted as UUID
- May require additional explanation to team members unfamiliar with the library
- Slightly lower collision resistance compared to UUID (but still very high)
- Limited built-in features compared to more comprehensive ID libraries
Code Examples
Generate a default Nanoid:
import { nanoid } from 'nanoid';
const id = nanoid(); // => "V1StGXR8_Z5jdHi6B-myT"
Generate a Nanoid with custom length:
import { nanoid } from 'nanoid';
const id = nanoid(10); // => "IRFa-VaY2b"
Generate a Nanoid with custom alphabet:
import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('1234567890abcdef', 10);
const id = nanoid(); // => "4f90d13a42"
Getting Started
To use Nanoid in your project, first install it via npm:
npm install nanoid
Then, import and use it in your JavaScript code:
import { nanoid } from 'nanoid';
// Generate a Nanoid
const id = nanoid();
console.log(id); // Outputs a unique ID like "V1StGXR8_Z5jdHi6B-myT"
For more advanced usage, refer to the Nanoid documentation for customization options and best practices.
Competitor Comparisons
K-Sortable Globally Unique IDs
Pros of KSUID
- Sortable and time-ordered, allowing for easy chronological sorting
- Includes timestamp information, useful for tracking creation time
- Longer length (27 characters) provides higher uniqueness guarantee
Cons of KSUID
- Larger size (27 characters) compared to NanoID's default 21 characters
- More complex implementation, potentially slower generation
- Less flexible in terms of customizing ID length or character set
Code Comparison
NanoID:
import { nanoid } from 'nanoid';
const id = nanoid(); // "V1StGXR8_Z5jdHi6B-myT"
KSUID:
import "github.com/segmentio/ksuid"
id := ksuid.New()
fmt.Printf("%s\n", id) // "0ujtsYcgvSTl8PAuAdqWYSMnLOv"
Summary
NanoID focuses on simplicity and flexibility, offering a compact ID with customizable length and character set. KSUID prioritizes sortability and timestamp inclusion, resulting in longer IDs with built-in time ordering. Choose NanoID for lightweight, flexible ID generation, and KSUID when chronological sorting and timestamp information are crucial.
Short id generator. Url-friendly. Non-predictable. Cluster-compatible.
Pros of shortid
- Longer history and more established in the ecosystem
- Supports custom alphabets for ID generation
- Provides a synchronous API for ID generation
Cons of shortid
- No longer actively maintained (last commit in 2017)
- Larger bundle size compared to nanoid
- Less secure random number generation
Code Comparison
shortid:
const shortid = require('shortid');
const id = shortid.generate();
nanoid:
const { nanoid } = require('nanoid');
const id = nanoid();
Summary
While shortid has been a popular choice for generating short, unique identifiers in JavaScript projects, nanoid has emerged as a more modern and efficient alternative. nanoid offers better performance, smaller bundle size, and improved security through the use of hardware random number generators when available.
shortid's main advantages lie in its established presence in many existing projects and its support for custom alphabets. However, its lack of recent updates and maintenance makes it less suitable for new projects.
nanoid, on the other hand, is actively maintained, has a smaller footprint, and provides better security. It also offers a simpler API and is generally considered the more recommended choice for current and future projects requiring unique ID generation.
Collision-resistant ids optimized for horizontal scaling and performance.
Pros of cuid
- Designed for horizontal scalability and high-performance in distributed systems
- Includes a timestamp component, allowing for time-based sorting
- Offers collision resistance across multiple machines and processes
Cons of cuid
- Longer ID length (25 characters) compared to nanoid's default (21 characters)
- More complex implementation, which may impact performance in some scenarios
- Less customizable in terms of ID length and character set
Code Comparison
nanoid:
import { nanoid } from 'nanoid';
const id = nanoid(); // => "V1StGXR8_Z5jdHi6B-myT"
cuid:
import cuid from 'cuid';
const id = cuid(); // => "ck0y3qk8e0000udocop0lj8rm"
Both nanoid and cuid are popular libraries for generating unique identifiers. nanoid focuses on simplicity, performance, and customization, while cuid emphasizes distributed systems and time-based sorting. nanoid generates shorter IDs by default and offers more flexibility in terms of length and character set. cuid, on the other hand, provides better support for horizontal scaling and includes a timestamp component. The choice between the two depends on specific project requirements, such as scalability needs, ID length preferences, and performance considerations.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Nano ID
English | Ð ÑÑÑкий | ç®ä½ä¸æ | Bahasa Indonesia
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. 116 bytes (minified and brotlied). 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 to over 20 programming languages.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
  Made at Evil Martians, product consulting for developer tools.
Table of Contents
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 two 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 4 times smaller than
uuid/v4
package: 130 bytes instead of 423.
Benchmark
$ node ./test/benchmark.js
crypto.randomUUID 7,619,041 ops/sec
uuid v4 7,436,626 ops/sec
@napi-rs/uuid 4,730,614 ops/sec
uid/secure 4,729,185 ops/sec
@lukeed/uuid 4,015,673 ops/sec
nanoid 3,693,964 ops/sec
customAlphabet 2,799,255 ops/sec
nanoid for browser 380,915 ops/sec
secure-random-string 362,316 ops/sec
uid-safe.sync 354,234 ops/sec
shortid 38,808 ops/sec
Non-secure:
uid 11,872,105 ops/sec
nanoid/non-secure 2,226,483 ops/sec
rndm 2,308,044 ops/sec
Test configuration: Framework 13 7840U, Fedora 39, Node.js 21.6.
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 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 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. -
Well-documented: all Nano ID hacks are documented. See comments in the source.
-
Vulnerabilities: to report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
Install
npm install nanoid
Nano ID 5 works only with ESM projects, in tests or Node.js scripts.
For CommonJS you need to use latest Node.js 20 or 22
with --experimental-require-module
:
node --experimental-require-module app.js
Or you can use Nano ID 3.x (we still support it):
npm install 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.
import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
API
Nano ID has 2 APIs: normal 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.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
If you want to reduce the ID size (and increase collisions probability), you can pass the size as an argument.
nanoid(10) //=> "IRFa-VaY2b"
Donât forget to check the safety of your ID size in our ID collision probability calculator.
You can also use a custom alphabet or a random generator.
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 it for environments without hardware random generators.
import { nanoid } from 'nanoid/non-secure'
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Custom Alphabet or Size
customAlphabet
returns a function that allows you to create nanoid
with your own alphabet and ID size.
import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid() //=> "4f90d13a42"
import { customAlphabet } from 'nanoid/non-secure'
const nanoid = customAlphabet('1234567890abcdef', 10)
user.id = nanoid()
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:
import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid(5) //=> "f01a2"
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:
import { customRandom } from 'nanoid'
const rng = seedrandom(seed)
const nanoid = customRandom('abcdef', 10, size => {
return (new Uint8Array(size)).map(() => 256 * rng())
})
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 customRandom
,
you can get the default alphabet using the urlAlphabet
.
const { customRandom, urlAlphabet } = require('nanoid')
const nanoid = customRandom(urlAlphabet, 10, random)
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.
function Todos({todos}) {
return (
<ul>
{todos.map(todo => (
<li key={nanoid()}> /* DONâT DO IT */
{todo.text}
</li>
))}
</ul>
)
}
You should rather try to reach for stable ID inside your list item.
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
In case you donât have stable IDs you'd rather use index as key
instead of nanoid()
:
const todoItems = todos.map((text, index) =>
<li key={index}> /* Still not recommended but preferred over nanoid().
Only do this if items have no stable IDs. */
{text}
</li>
)
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.
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
.
- 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'
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:
db.put({
_id: 'id' + nanoid(),
â¦
})
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.
import { nanoid } from 'nanoid/non-secure'
nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Note: non-secure IDs are more prone to collision attacks.
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.
$ npx nanoid
npx: installed 1 in 0.63s
LZfXLFzPPR4NNrgjlWDxn
Size of generated ID can be specified with --size
(or -s
) option:
$ npx nanoid --size 10
L3til0JS4z
Custom alphabet can be specified with --alphabet
(or -a
) option
(note that in this case --size
is required):
$ npx nanoid --alphabet abc --size 15
bccbcabaabaccab
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.
- C#
- C++
- Clojure and ClojureScript
- ColdFusion/CFML
- Crystal
- Dart & Flutter
- Deno
- Elixir
- Go
- Haskell
- Haxe
- Janet
- Java
- Kotlin
- MySQL/MariaDB
- Nim
- OCaml
- Perl
- PHP
- Python native implementation with dictionaries and fast implementation (written in Rust)
- Postgres Extension and Native Function
- R (with dictionaries)
- Ruby
- Rust
- Swift
- Unison
- V
- Zig
For other environments, CLI is available to generate IDs from a command line.
Tools
- ID size calculator shows collision probability when adjusting the ID alphabet or size.
nanoid-dictionary
with popular alphabets to use withcustomAlphabet
.nanoid-good
to be sure that your ID doesnât contain any obscene words.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot