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

Overview

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.
  • Fast. It is 2 times faster than UUID.
  • 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 three 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 less than uuid/v4 package: 130 bytes instead of 483.
  3. Because of memory allocation tricks, Nano ID is 2 times faster than UUID.

Benchmark

$ node ./test/benchmark.js
crypto.randomUUID         25,603,857 ops/sec
@napi-rs/uuid              9,973,819 ops/sec
uid/secure                 8,234,798 ops/sec
@lukeed/uuid               7,464,706 ops/sec
nanoid                     5,616,592 ops/sec
customAlphabet             3,115,207 ops/sec
uuid v4                    1,535,753 ops/sec
secure-random-string         388,226 ops/sec
uid-safe.sync                363,489 ops/sec
cuid                         187,343 ops/sec
shortid                       45,758 ops/sec

Async:
nanoid/async                  96,094 ops/sec
async customAlphabet          97,184 ops/sec
async secure-random-string    92,794 ops/sec
uid-safe                      90,684 ops/sec

Non-secure:
uid                       67,376,692 ops/sec
nanoid/non-secure          2,849,639 ops/sec
rndm                       2,674,806 ops/sec

Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 34, Node.js 16.10.

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

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'

In Node.js you can use CommonJS import:

const { nanoid } = require('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 the faster non-secure generator.

import { nanoid } from 'nanoid/non-secure'
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"

Custom Alphabet or Size

customAlphabet 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"

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.

Customizable asynchronous and non-secure APIs are 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()

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.

Usage

IE

If you support IE, you need to transpile node_modules by Babel and add crypto alias:

// polyfills.js
if (!window.crypto) {
  window.crypto = window.msCrypto
}
import './polyfills.js'
import { nanoid } from 'nanoid'

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

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'

Rollup

For Rollup you will need @rollup/plugin-node-resolve to bundle browser version of this library and @rollup/plugin-replace to replace process.env.NODE_ENV:

  plugins: [
    nodeResolve({
      browser: true
    }),
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
  ]

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(),})

Mongoose

const mySchema = new Schema({
  _id: {
    type: String,
    default: () => 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

If you want to change alphabet or ID size, you should use nanoid-cli.

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

Comments
  • Recently installed in an Expo 37/RN app, getting TypeError: null is not an object (evaluating 'RNGetRandomValues.getRandomBase64')

    Recently installed in an Expo 37/RN app, getting TypeError: null is not an object (evaluating 'RNGetRandomValues.getRandomBase64')

    As stated in the title, recently installed it into an Expo 37 app as I was all of a sudden getting errors using uuid.V4. Followed the instructions and made sure I installed and imported 'react-native-get-random-values' (both at the top of my index.js entry point of the app, and every where else I used nanoid.

    On starting the app I get this error:

    TypeError: null is not an object (evaluating 'RNGetRandomValues.getRandomBase64')
    
    getRandomValues
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126457:35
    nanoid
        index.browser.js:80:2
    arr.map$argument_0
        grape-varietals.js:10:18
    map
        [native code]:0
    <global>
        grape-varietals.js:9:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126380:39
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126309:36
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126059:61
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126024:53
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:124002:50
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:123965:50
    loadModuleImplementation
        require.js:322:6
    <global>
        AppEntry.js:3
    loadModuleImplementation
        require.js:322:6
    guardedLoadModule
        require.js:201:45
    global code
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:165136:4
    
    rng
        rng-browser.js:16:7
    v4
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126911:63
    arr.map$argument_0
        grape-varietals.js:9:18
    map
        [native code]:0
    <global>
        grape-varietals.js:8:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126376:39
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126307:36
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126057:61
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:126022:53
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:124000:50
    loadModuleImplementation
        require.js:322:6
    <unknown>
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:123965:50
    loadModuleImplementation
        require.js:322:6
    <global>
        AppEntry.js:3
    loadModuleImplementation
        require.js:322:6
    guardedLoadModule
        require.js:201:45
    global code
        AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false:165602:4
    

    I am implementing in my code like this:

    import 'react-native-get-random-values';
    import { nanoid } from 'nanoid';
    // other code
    const createVarietalArray = (arr, color, common) => {
      return arr.map(v => new Varietal(nanoid(), color, v, false, common));
    };
    
    const COMMON_RED = createVarietalArray(redVarietals.common, 'red', true);
    

    Any idea what might be causing this?

    opened by PaulHaze 57
  • es-module friendly entry provide

    es-module friendly entry provide

    Basically, require is not available in browser, for which the js source code files are unable to use directly in modern Browser HTML context where ECMA Modules Feature has been supported natively.

    I've also noticed that you are using parcel to build up a es style module file for usage in demo html file.

    Why not directly make it available through es-module-aware entry in package.json: https://github.com/rollup/rollup/wiki/pkg.module

    opened by chigix 47
  • How to load into browser environment via script tag?

    How to load into browser environment via script tag?

    Not clear how to run nanoid within browser, which file should I load via script tag? Are there dist or .min.js build available?

    Think this information would be valuable for documentation (README.md) as well, because right now all examples show only Node.js require synax.

    opened by pqr 45
  • 4.0 doesn't support require in nodeJS

    4.0 doesn't support require in nodeJS

    const { customAlphabet } = require('nanoid') ^

    Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Administrator\Documents\serverws\node_modules.pnpm\[email protected]\node_modules\nanoid\index.js from C:\Users\Administrator\Documents\serverws\routes.js not supported.

    opened by bitdom8 27
  • TypeError: (0 , _nanoid.nanoid) is not a function

    TypeError: (0 , _nanoid.nanoid) is not a function

    I trying upgrade nanoid from 2.x to 3.x in CRA environment

    The export value from nanoid is always undefined

    And i got error when running below jest test

    import { nanoid } from 'nanoid';
    it('Should work', () => {
      console.log('nanoid is ', nanoid);
      const genId = nanoid();
      expect(() => genId()).not.toThrow();
    });
    

    Console message

    console.log src/services/spotify/auth/__tests__/authorize.test.ts:14
        nanoid is  undefined
    TypeError: (0 , _nanoid.nanoid) is not a function
    
    

    Also i try below test

    import * as nanoid from 'nanoid';
    
    it('Should work', () => {
      console.log('nanoid is ', nanoid);
      const genId = nanoid.nanoid();
      expect(() => genId()).not.toThrow();
    });
    

    Console message

      console.log src/services/spotify/auth/__tests__/authorize.test.ts:14
        nanoid is  { default: 'index.cjs' }
    TypeError: nanoid.nanoid is not a function
    
    opened by davidNHK 27
  • ES module browser build expects

    ES module browser build expects "process" global

    When running this package on jspm, it will give "process is undefined" because of the process check in the index.browser.js file.

    The assumption of the browser environment shouldn't be based on the proces global existing. Adding a typeof process !== 'undefined' check would fix this issue.

    opened by guybedford 26
  • [TYPESCRIPT] Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

    [TYPESCRIPT] Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

    Hi, I got this error when import nanoid to my project:

    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /todo-api/node_modules/nanoid/index.js
    require() of ES modules is not supported.
    require() of /todo-api/node_modules/nanoid/index.js from /todo-api/controllers/todo-apis/todo-apis.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /todo-api/node_modules/nanoid/package.json.
    
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
        at Module.load (internal/modules/cjs/loader.js:928:32)
        at Function.Module._load (internal/modules/cjs/loader.js:769:14)
        at Module.require (internal/modules/cjs/loader.js:952:19)
        at require (internal/modules/cjs/helpers.js:88:18)
        at Object.<anonymous> (/todo-api/controllers/todo-apis/todo-apis.ts:1:1)
        at Module._compile (internal/modules/cjs/loader.js:1063:30)
        at Module.m._compile (/todo-api/node_modules/ts-node/src/index.ts:1056:23)
        at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
        at Object.require.extensions.<computed> [as .ts] (/todo-api/node_modules/ts-node/src/index.ts:1059:12)
    

    Please help! Please let me know if you need more information. Thanks.

    opened by haintwork 21
  • Error: No valid exports main found for '/path/to/nanoid'

    Error: No valid exports main found for '/path/to/nanoid'

    As initially described at https://github.com/ai/nanoid/issues/206#issuecomment-622967848 , I am getting a MODULE_NOT_FOUND error with [email protected] and [email protected].

    Here is the repro: https://github.com/cansin/nanoid-module-not-found-repro

    And a sample run on my local:

    cansin@localhost nanoid-repro % node --version
    v13.2.0
    cansin@localhost nanoid-repro % yarn --version
    1.22.4
    cansin@localhost nanoid-repro % yarn install
    yarn install v1.22.4
    [1/5] 🔍  Validating package.json...
    [2/5] 🔍  Resolving packages...
    [3/5] 🚚  Fetching packages...
    [4/5] 🔗  Linking dependencies...
    [5/5] 🔨  Building fresh packages...
    
    ✨  Done in 0.09s.
    cansin@localhost nanoid-repro % node index.js 
    internal/modules/cjs/loader.js:614
      throw e;
      ^
    
    Error: No valid exports main found for '/Users/cansin/code/nanoid-reprod/node_modules/nanoid'
        at resolveExportsTarget (internal/modules/cjs/loader.js:611:9)
        at applyExports (internal/modules/cjs/loader.js:492:14)
        at resolveExports (internal/modules/cjs/loader.js:541:12)
        at Function.Module._findPath (internal/modules/cjs/loader.js:643:22)
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:941:27)
        at Function.Module._load (internal/modules/cjs/loader.js:847:27)
        at Module.require (internal/modules/cjs/loader.js:1016:19)
        at require (internal/modules/cjs/helpers.js:69:18)
        at Object.<anonymous> (/Users/cansin/code/nanoid-reprod/index.js:1:20)
        at Module._compile (internal/modules/cjs/loader.js:1121:30) {
      code: 'MODULE_NOT_FOUND'
    }
    

    Thanks.

    opened by cansin 20
  • Allow react-native alternative for a async random number generator

    Allow react-native alternative for a async random number generator

    My colleagues are building a react-native application. We use nanoid as part of our login flow. While introducing our common solution I got an issues reported that the current usage of nanoid breaks the application for them. The reason for this is the exception which is being thrown in index.browser.js. (Interestingly the same exception should be probably added to the async layer - which is not yet implemented.) Back to the issue. We could probably think of adding a react-native entry as supported by the Metro bundler (used by React Native) to use a special random number generator in async.

    For our login flow I am fine with using the async API. But still this has to work without throwing errors in React Native.

    The solution described in the Readme is a good solution for plain react-native projects, but does not correctly work in these cross-target libraries. I do not want to make any native code for iOS/Android a dependency to our pure JS library.

    So I wondered how this can be probably look like for nanoid if supported out of the box. I just replaced the random number generator with the code listed in the readme. Do you think it would be that simple?

    This PR is meant as a suggestions and discussion starting point. Thanks for listening.

    opened by swernerx 20
  • Recommended dictionary for a 256 character set?

    Recommended dictionary for a 256 character set?

    I would like to have a dictionary of well chosen 256 characters to generate a UUID V4-compliant as short as possible (maybe 6 or 8 I don't know). Can you add a recommended dictionary for this? Maybe using the greek alphabet also, but this will not be enough. What about emoji?

    opened by slimhk45 18
  • why is { nanoid } not exported as default?

    why is { nanoid } not exported as default?

    in the spirit of nano-sized things, why is nanoid not exported as 'default' to allow smaller import?

    import nano from 'nanoid'; // doesn't work currently
    
    opened by iambumblehead 16
  • GUID comparison

    GUID comparison

    Greetings,

    I am compiling a GUID summary sheet which tries to aggregate different dimensions with the intent to help engineers pick the right generator.

    Would you be kind enough to help me validate the Nanoid column and point to any issues?

    Thank you

    image

    opened by orefalo 2
  • v4 can't be imported in node

    v4 can't be imported in node

    Hello,

    I'm not knowledgeable at all in all the module formats / import mess of javascript / node, but I'm using KeystoneJS and I import nanoid in it. Since version 4 (2 days ago), I have this error :

    Error [ERR_REQUIRE_ESM]: require() of ES Module /node_modules/nanoid/async/index.js from schema.ts not supported. Instead change the require of index.js in schema.ts to a dynamic import() which is available in all CommonJS modules.

    This is how I've always imported nanoid :

    import { nanoid } from 'nanoid/async';

    Reverting to 3.3.4 works. I see in the commit comment that you removed CJS support, but as I understand, using this import statement, I'm using the new thingy module stuff, not CJS which uses require instead, and you have "type: module" in your package.json, so I really don't know what's wrong here.

    Any idea what I'm doing wrong ? Thanks !

    opened by g012 87
  • Underscore is sometimes an unsafe character

    Underscore is sometimes an unsafe character

    Hello there,

    Just wanted to open this issue to discuss the underscore character. It is unsafe if used at the very end of an URL on GitHub. (I also tested it on Twitter but they handle it correctly.)

    Here's an example: https://example.com/abcdefgh_

    I noticed this problem because I use https://www.npmjs.com/package/react-markdown in a project and it rendered a link in this broken way which did ultimately cause problems for a user. If it is happening to me then I'm sure other people are experiencing it too (perhaps unwittingly since it is kinda rare, 1/64 chance).

    If a non-_ character is added at the end then the link is no longer broken. https://example.com/abcdefgh_/

    Anyway, I wanted to start a discussion here to raise the problem. Perhaps the react-markdown package can be improved to handle this situation? Are there other libraries and packages that may misbehave in a similar way?

    I am going to use a custom alphabet in my project. Although I find that the API for using a custom alphabet is a bit cumbersome. I will open a PR soon with a suggested API change (but I need help to finish it).

    Thanks!

    opened by stefansundin 4
Releases(3.0.0)
  • 3.0.0(Mar 26, 2020)

    Nano ID 3.0 is the biggest release in the project history. Unfortunately, you will need to change the code of your application. But the changes are very small in most cases. In return, you will have better performance, smaller size, ES modules and TypeScript support.

    Known Issues

    • Only Create React App 4.0 supports dual ESM/CJS modules.

    Simple Case

    In simple cases, you just need to change default import to named import.

    - import nanoid from 'nanoid'
    + import { nanoid } from 'nanoid'
    
    nanoid() //=> "sSAi9F8yakJZPxOCr_WFb"
    nanoid(5) //=> "ISe9l"
    

    If you support IE, you need to transpile node_modules by Babel.

    Non-secure and asynchronous Nano ID need only import changes as well.

    - import nanoid from 'nanoid/non-secure'
    + import { nanoid } from 'nanoid/non-secure'
    
    nanoid() //=> "sSAi9F8yakJZPxOCr_WFb"
    
    - import nanoid from 'nanoid/async'
    + import { nanoid } from 'nanoid/async'
    
    nanoid().then(id => {
      id //=> "sSAi9F8yakJZPxOCr_WFb"
    })
    

    TypeScript

    Remove @types/nanoid if you have it. Nano ID now have built-in types.

    npm uninstall @types/nanoid
    

    React Native

    For Expo you need to load the file by direct path:

    - import nanoid from "nanoid/async"
    + import { nanoid } from "nanoid/async/index.native.js"
    

    For the non-Expo environment:

    1. Change polyfill for hardware random generator from expo-random to react-native-get-random-values.

    2. Use sync Nano ID instead of async.

      + import 'react-native-get-random-values'
      
      - import nanoid from 'nanoid/async'
      + import { nanoid } from 'nanoid'
      
        async function createUser () {
          const user = new User()
      -   user.id = await nanoid()
      +   user.id = nanoid()
          return await user.save()
        }
      

    URL-Safe Alphabet

    Our default URL-safe alphabet was moved as named export to nanoid path:

    - import url from 'nanoid/url'
    + import { urlAlphabet } from 'nanoid'
    

    Custom Alphabet

    Now we use the currying API to change the alphabet. It improves performance by pre-calculating some caches for a new alphabet.

    We hope the new API will be more readable compare to the old unclear “generate” word.

    - import nanoidGenerate from 'nanoid/generate'
    + import { customAlphabet } from 'nanoid'
    
    + const nanoid = customAlphabet(alphabet, 10)
    
    - nanoidGenerate(alphabet, 10) //=> "0476921501"
    + nanoid() //=> "0476921501"
    

    Non-secure and asynchronous APIs were also changed:

    - import nanoidGenerate from 'nanoid/async/generate'
    + import { customAlphabet } from 'nanoid/async'
    
    + const nanoid = customAlphabet(alphabet, 10)
    

    Custom Random Generator

    Custom random generator API now is based on currying as well.

    - import nanoidFormat from 'nanoid/format'
    - import url from 'nanoid/url'
    + import { customRandom, urlAlphabet } from 'nanoid'
    
    + const nanoid = customRandom(urlAlphabet, 10, seedRandom)
    
    - nanoidGenerate(seedRandom, url, 10) //=> "sSAi9F8yak"
    + nanoid() //=> "sSAi9F8yak"
    

    We removed a custom random generator from asynchronous API because we didn’t see that somebody used it.

    New Features

    A few good reasons, why you should migrate to Nano ID 3.0:

    • The size was decreased by 10% from 119 to 108 bytes.
    • We got full TypeScript support. We use check-dts to test out .d.ts files.
      id: number = nanoid() // throws Type 'string' is not assignable to type 'number'.
      
    • Nano ID now has out-of-the-box ES modules support and extra file to load Nano ID from jsDelivr (use it only for experiments, because of the bad loading performance). Dual ESM/CommonJS packaging is provided by dual-publish and will work in Node.js ≥12, webpack, Parcel, Rollup, and React Native.
      import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
      
    Source code(tar.gz)
    Source code(zip)
Owner
Andrey Sitnik
The creator of Autoprefixer, @postcss, @browserslist, and @logux
Andrey Sitnik
Backend API Rest application for ShortLink, a URL shortening service where you enter a valid URL and get back an encoded URL

ShortLink - The Shortest URL (API) Sobre o Projeto | Como Usar | Importante! Sobre o projeto The Shortest URL é um projeto back-end de ShortLink, um s

Bruno Weber 2 Mar 22, 2022
A super tiny Javascript library to make DOM elements draggable and movable. ~500 bytes and no dependencies.

dragmove.js A super tiny Javascript library to make DOM elements draggable and movable. Has touch screen support. Zero dependencies and 500 bytes Gzip

Kailash Nadh 814 Dec 29, 2022
Digital Identifier is a secure, decentralized, anonymous and tampered proof way of maintaining and verifying all essential identity-based documents to create a unique digital identity of a person.

Digital Identifier ?? To design and develop a secure, decentralized, anonymous and tampered proof way of maintaining and verifying all essential ident

Mukul Kolpe 4 Dec 17, 2022
This package generates a unique ID/String for different browsers. Like chrome, Firefox and any other browsers which supports canvas and audio Fingerprinting.

Broprint.js The world's easiest, smallest and powerful visitor identifier for browsers. This package generates a unique ID/String for different browse

Rajesh Royal 68 Dec 25, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
A Secure Web Proxy. Which is fast, secure, and easy to use.

Socratex A Secure Web Proxy. Which is fast, secure, and easy to use. This project is under active development. Everything may change soon. Socratex ex

Leask Wong 220 Dec 15, 2022
Convert some JavaScript/TypeScript code string into a .d.ts TypeScript Declaration code string

convert-to-dts Converts the source code for any .js or .ts file into the equivalent .d.ts code TypeScript would generate. Usage import { convertToDecl

Lily Scott 11 Mar 3, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Little Javascript / Typescript library for validating format of string like email, url, password...

String-Validators Little Javascript / Typescript library for validating format of string like email, url, password... Signaler un Bug · Proposer une F

J.Delauney 3 Oct 14, 2022
Unique guid generator pure Javascript.

Guid Generator Create unique Guids. Usage For client Javascript import { Guid } from "../src/guid"; Guid.NewGuid(); // 1q6G3w1U-8F0D-8p9R-7m6m-5b5B7G

Yahya Altıntop 11 Nov 1, 2022
NFT Art Generator made to create random unique art and their metadeta for NFTS.

Welcome to HashLips ?? All the code in these repos was created and explained by HashLips on the main YouTube channel. To find out more please visit: ?

Haadi Raja 2 Dec 11, 2022
Password Generator - A fast, simple and powerful open-source utility tool for generating strong, unique and random passwords

A fast, simple and powerful open-source utility tool for generating strong, unique and random passwords. Password Generator is free to use as a secure password generator on any computer, phone, or tablet.

Sebastien Rousseau 11 Aug 3, 2022
👌A useful zero-dependencies, less than 434 Bytes (gzipped), pure JavaScript & CSS solution for drop an annoying pop-ups confirming the submission of form in your web apps.

Throw out pop-ups confirming the submission of form! A useful zero-dependencies, less than 434 Bytes (gzipped), pure JavaScript & CSS solution for dro

Vic Shóstak 35 Aug 24, 2022
A tiny isomorphic fast function for generating a cryptographically random hex string.

ZeptoID A tiny isomorphic fast function for generating a cryptographically random hex string. Accoding to this calculator one would have to generate i

Fabio Spampinato 9 Oct 24, 2022
2 player tictactoe-hosting TCP server in 640 bytes

tictactinytoe 2 player tictactoe-hosting TCP server in 640 bytes: F=_=>{x=o=z=0;t=1};F();require("net").createServer(c=>{h="\n";w=s=>c.write(s+h);if(o

Shivam Mamgain 25 Jul 27, 2022
A POC of a Discord.js bot that sends 3D rendering instructions to a Go server through gRPC which responds with the image bytes which are then sent back on Discord.

A POC of a Discord.js bot that sends 3D rendering instructions to a Go server through gRPC which responds with the image bytes which are then sent back on Discord.

Henrique Corrêa 5 Jan 8, 2022
Tiny API that provide product/library name for a URL

JSer.info Product Name API Tiny API that provide product/library name for a URL. Usage Supported All products. curl https://jser-product-name.deno.dev

JSer.info 6 Oct 21, 2022
A tiny, SSR-friendly hook for listening to gamepad events.

useGamepadEvents useGamepadEvents is a tiny, SSR-friendly hook for listening to gamepad events. It's a wrapper around the Gamepad API designed for fir

Hayden Bleasel 2 Oct 2, 2022