• Stars
    star
    22,698
  • Rank 958 (Top 0.02 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Nano ID

Nano ID logo by Anton Lovchikov

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. 130 bytes (minified and gzipped). 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 20 programming languages.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"

Supports modern browsers, IE with Babel, Node.js and React Native.

Sponsored by Evil Martians

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:

  1. Nano ID uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.
  2. Nano ID code is 4 times smaller than uuid/v4 package: 130 bytes instead of 423.

Benchmark

$ node ./test/benchmark.js
crypto.randomUUID         21,119,429 ops/sec
uuid v4                   20,368,447 ops/sec
@napi-rs/uuid             11,493,890 ops/sec
uid/secure                 8,409,962 ops/sec
@lukeed/uuid               6,871,405 ops/sec
nanoid                     5,652,148 ops/sec
customAlphabet             3,565,656 ops/sec
secure-random-string         394,201 ops/sec
uid-safe.sync                393,176 ops/sec
shortid                       49,916 ops/sec

Async:
nanoid/async                 135,260 ops/sec
async customAlphabet         136,059 ops/sec
async secure-random-string   135,213 ops/sec
uid-safe                     119,587 ops/sec

Non-secure:
uid                       58,860,241 ops/sec
nanoid/non-secure          2,744,615 ops/sec
rndm                       2,718,063 ops/sec

Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 36, Node.js 18.9.

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 the crypto 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.

    Nano ID 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 --save nanoid

Nano ID 4 works only with ESM projects, in tests or Node.js scripts. For CommonJS you need Nano ID 3.x (we still support it):

npm install --save 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'

Nano ID provides ES modules. You do not need to do anything to use Nano ID as ESM in webpack, Rollup, Parcel, or Node.js.

import { nanoid } from 'nanoid'

API

Nano ID has 3 APIs: normal (blocking), asynchronous, 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.

Async

To generate hardware random bytes, CPU collects electromagnetic noise. For most cases, entropy will be already collected.

In the synchronous API during the noise collection, the CPU is busy and cannot do anything useful (for instance, process another HTTP request).

Using the asynchronous API of Nano ID, another code can run during the entropy collection.

import { nanoid } from 'nanoid/async'

async function createUser() {
  user.id = await nanoid()
}

Read more about entropy collection in crypto.randomBytes docs.

Unfortunately, you will lose Web Crypto API advantages in a browser if you use the asynchronous API. So, currently, in the browser, you are limited with either security (nanoid), asynchronous behavior (nanoid/async), or non-secure behavior (nanoid/non-secure) that will be explained in the next part of the documentation.

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/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()

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)

Asynchronous and non-secure APIs are not available for customRandom.

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.

  1. Check react-native-get-random-values docs and install it.
  2. 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.

Jest

Jest test runner with jest-environment-jsdom will use browser’s version of Nano ID. You will need polyfill for Web Crypto API.

import { randomFillSync } from 'crypto'

window.crypto = {
  getRandomValues(buffer) {
    return randomFillSync(buffer)
  }
}

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.

For other environments, CLI is available to generate IDs from a command line.

Tools

More Repositories

1

easings.net

Easing Functions Cheat Sheet
CSS
7,459
star
2

size-limit

Calculate the real cost to run your JS app or lib to keep good performance. Show error in pull request if the cost exceeds the limit.
JavaScript
6,345
star
3

visibilityjs

Wrapper for the Page Visibility API
JavaScript
1,817
star
4

nanoevents

Simple and tiny (107 bytes) event emitter library for JavaScript
TypeScript
1,385
star
5

autoprefixer-rails

Autoprefixer for Ruby and Ruby on Rails
Ruby
1,217
star
6

nanocolors

Use picocolors instead. It is 3 times smaller and 50% faster.
JavaScript
870
star
7

audio-recorder-polyfill

MediaRecorder polyfill to record audio in Edge and Safari
JavaScript
554
star
8

webp-in-css

PostCSS plugin and tiny JS script (131 bytes) to use WebP in CSS background
JavaScript
346
star
9

offscreen-canvas

Polyfill for OffscreenCanvas to move Three.js/WebGL/2D canvas to Web Worker
JavaScript
327
star
10

convert-layout

JS library to convert text from one keyboard layout to other
JavaScript
247
star
11

ssdeploy

Netlify replacement to deploy simple websites with better flexibility, speed and without vendor lock-in
JavaScript
193
star
12

nanodelay

A tiny (37 bytes) Promise wrapper around setTimeout
JavaScript
179
star
13

environment

My home config, scripts and installation process
Shell
179
star
14

dual-publish

Publish JS project as dual ES modules and CommonJS package to npm
JavaScript
178
star
15

autoprefixer-core

autoprefixer-core was depreacted, use autoprefixer
JavaScript
136
star
16

nanospy

Spy and mock methods in tests with great TypeScript support
TypeScript
135
star
17

transition-events

jQuery plugin to set listeners to CSS Transition animation end or specific part
JavaScript
133
star
18

check-dts

Unit tests for TypeScript definitions in your JS open source library
JavaScript
130
star
19

evil-blocks

Tiny framework for web pages to split your app to separated blocks
JavaScript
125
star
20

rails-sass-images

Sass functions and mixins to inline images and get images size
Ruby
115
star
21

compass.js

Compass.js allow you to get compass heading in JavaScript by PhoneGap, iOS API or GPS hack.
CoffeeScript
112
star
22

evil-front

Helpers for frontend from Evil Martians
Ruby
101
star
23

rake-completion

Bash completion support for Rake
Shell
64
star
24

yaspeller-ci

Fast spelling check for Travis CI
JavaScript
61
star
25

jquery-cdn

Best way to use latest jQuery in Ruby app
Ruby
59
star
26

sitnik.ru

My homepage content and scripts
JavaScript
57
star
27

pages.js

CoffeeScript
44
star
28

fotoramajs

Fotorama for Ruby on Rails
Ruby
44
star
29

keyux

JS library to improve keyboard UI of web apps
TypeScript
41
star
30

about-postcss

Keynotes about PostCSS
Ruby
29
star
31

autohide-battery

GNOME Shell extension to hide battery icon in top panel, if battery is fully charged and AC is connected.
JavaScript
27
star
32

darian

Darian Mars calendar converter
Ruby
25
star
33

plain_record

Data persistence with human readable and editable storage.
Ruby
24
star
34

better-node-test

The CLI shortcut for node --test runner with TypeScript
JavaScript
24
star
35

evolu-lang

Programming language to automatically generate programs by evolution (genetic programming).
JavaScript
22
star
36

martian-logux-demo

TypeScript
17
star
37

twitter2vk

Script to automatically repost statuses from Twitter to VK (В Контакте)
Ruby
16
star
38

ci-job-number

Return CI job number to run huge tests only on first job
JavaScript
15
star
39

hide-keyboard-layout

GNOME Shell extension to hide keyboard layout indicator in status bar
JavaScript
15
star
40

load-resources

Load all JS/CSS files from site website
JavaScript
15
star
41

print-snapshots

Print Jest snapshots to check CLI output of your tool
JavaScript
15
star
42

susedko

Fedora CoreOS ignition config for my home server
JavaScript
14
star
43

file-container

Store different languages in one source file
JavaScript
14
star
44

autoprefixer-cli

CLI for Autoprefixer
JavaScript
14
star
45

postcss-isolation

Fix global CSS with PostCSS
14
star
46

asdf-cache-action

A Github Action to install runtimes by asdf CLI with a cache
13
star
47

showbox

Keynote generator
JavaScript
11
star
48

d2na

D²NA language for genetic programming
Ruby
10
star
49

postcss-way

Keynotes about PostCSS way
9
star
50

gulp-bench-summary

Display gulp-bench results in nice table view
JavaScript
8
star
51

boilerplates

Boilerplate for my open source projects
8
star
52

anim2012

Доклад «Анимации по-новому — лень, гордыня и нетерпимость»
CSS
8
star
53

nanopurify

A tiny (from 337 bytes) HTML sanitizer
JavaScript
7
star
54

ai

6
star
55

rit3d

Доклад «Веб, теперь в 3D: Практика»
CSS
6
star
56

dis.spbstu.ru

Department homepage
Ruby
5
star
57

evolu-steam

Evolu Steam – evolutionary computation for JavaScript
JavaScript
5
star
58

jstransformer-lowlight

Lowlight support for JSTransformers
JavaScript
5
star
59

jest-ci

CLI for Jest test framework, but coverage only on first CI job
JavaScript
5
star
60

insomnis

Текст блогокниги «Инсомнис»
4
star
61

wsd2013

Презентация «Автопрефиксер: мир без CSS-префиксов»
Ruby
4
star
62

ruby2jar

Ruby2Jar builds JAR from a Ruby script
Ruby
3
star
63

showbox-ai

Sitnik’s theme for ShowBox
CSS
3
star
64

plague

Blog/book Plague engine
Ruby
3
star
65

showbox-bright

Shower Bright theme for Showbox
JavaScript
3
star
66

showbox-shower

Shower for ShowBox
JavaScript
2
star
67

on_the_islands

Ruby
2
star