Code Monkey home page Code Monkey logo

nanoid's Introduction

Nano ID

A port of nanoid to Deno

A tiny, secure, URL-friendly, unique string ID generator for JavaScript.

import { nanoid } from "https://deno.land/x/nanoid/mod.ts"
nanoid() //=> "lQLTBJKVRCuc"

Table of Contents

  1. Comparison with UUID
  2. Tools
  3. Security
  4. Usage
    1. JS
    2. Other Programming Languages
  5. CLI
    1. Installation
    2. Usage
  6. API
    1. Async
    2. Custom Alphabet or Length
    3. Custom Random Bytes Generator

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: 127 bytes instead of 435.
  3. Because of memory allocation tricks, Nano ID is 16% faster than UUID.

Tools

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 Web Crypto API. These modules use unpredictable hardware random generator.

Usage

JS

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 "https://deno.land/x/nanoid/mod.ts"
nanoid() //=> "lQLTBJKVRCuc"

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.

Other Programming Languages

Nano ID was ported to many languages. You can use these ports to have the same ID generators on client and server side.

Also, CLI tool is available to generate IDs from a command line.

$ deno run https://deno.land/x/nanoid/cli.ts

CLI

Installation

$ deno install --name nanoid https://deno.land/x/nanoid/cli.ts

Usage

  Usage:   nanoid
  Version: v2.0.0

  Description:

    A CLI for generating cryptographically-secure random IDs.

  Options:

    -h, --help                         - Show this help.                                                             
    -V, --version                      - Show the version number for this program.                                   
    -s, --size      <size:number>      - The desired length of IDs to be generated.                                  
    -a, --alphabet  <alphabet:string>  - The alphabet that IDs should be generated with.                             
    -n, --number    <n:number>         - The number of IDs to generate, if you would like more than one  (Default: 1)

  Commands:

    completions  - Generate shell completions.

API

Async

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 "https://deno.land/x/nanoid/async.ts";

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

Custom Alphabet or Length

If you want to change the ID's alphabet or length you can use the low-level generate module.

import { customAlphabet } from "https://deno.land/x/nanoid/customAlphabet.ts";
const nanoid = customAlphabet('1234567890abcdef', 10)
nanoid()  // => "4f90d13a42"

Alphabet must contain 256 symbols or less. Otherwise, the generator will not be secure.

Asynchronous API is also available:

import { customAlphabet } from "https://deno.land/x/nanoid/async.ts";
const nanoid = await customAlphabet('1234567890abcdef', 10);
async function createUser() {
  let id = nanoid();
}

Custom Random Bytes Generator

You can replace the default safe random generator using the format module. For instance, to use a seed-based generator.

import { customRandom } from "https://deno.land/x/nanoid/customRandom.ts";

function random (size) {
  const result = []
  for (let i = 0; i < size; i++) {
    result.push(randomByte())
  }
  return result;
}

const nanoid = customRandom(random, "abcdef", 10);
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 format, you can get the default alphabet from the url file.

import { customRandom } from "https://deno.land/x/nanoid/customRandom.ts";
import { urlAlphabet } from "https://deno.land/x/nanoid/urlAlphabet.ts";

const nanoid = customRandom(random, chars, 10);
nanoid(); // => "93ce_Ltuub"

Asynchronous API is also available:

import { customRandom } from 'https://deno.land/x/nanoid/async.ts';
import { urlAlphabet } from "https://deno.land/x/nanoid/urlAlphabet.ts";

function random (size) {
  return Promise.resolve(/*…*/)
}
const nanoid = await customRandom(random, url, 10);
async function createUser () {
  let id = nanoid(); // => "93ce_Ltuub"
}

nanoid's People

Contributors

ianfabs avatar sjc1117 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nanoid's Issues

Error trying to use the simple example

import nanoid from "https://deno.land/x/nanoid/mod.ts"
nanoid() //=> "lQLTBJKVRCuc"

Gives:

error: Uncaught ReferenceError: genereate is not defined
► generate.ts:22:16

22 export default genereate;

cli example broken as of deno 1.0.2

$ deno -V
deno 1.0.2
$ deno run https://deno.land/x/nanoid/cli.ts
Download https://deno.land/x/nanoid/cli.ts
Download https://deno.land/x/nanoid/mod.ts
Download https://deno.land/x/nanoid/customAlphabet.ts
Download https://deno.land/x/nanoid/url.ts
Download https://deno.land/std/flags/mod.ts
Warning Implicitly using master branch https://deno.land/std/flags/mod.ts
Download https://deno.land/std/testing/asserts.ts
Download https://deno.land/x/nanoid/random.ts
Download https://deno.land/x/nanoid/customRandom.ts
Warning Implicitly using master branch https://deno.land/std/testing/asserts.ts
Download https://deno.land/std/fmt/colors.ts
Download https://deno.land/std/testing/diff.ts
Warning Implicitly using master branch https://deno.land/std/testing/diff.ts
Warning Implicitly using master branch https://deno.land/std/fmt/colors.ts
Compile https://deno.land/x/nanoid/cli.ts
error: TS2739 [ERROR]: Type 'Reader & ReaderSync & Closer & { rid: number; }' is missing the following properties from type 'File': write, writeSync, seek, seekSync
const log = async (message: string, type: Deno.File = Deno.stdin) => {
                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    at https://deno.land/x/nanoid/cli.ts:15:37

TS2345 [ERROR]: Argument of type 'Writer & WriterSync & Closer & { rid: number; }' is not assignable to parameter of type 'Reader'.
  Property 'read' is missing in type 'Writer & WriterSync & Closer & { rid: number; }' but required in type 'Reader'.
  Deno.copy(Deno.stdout, buf);
            ~~~~~~~~~~~
    at https://deno.land/x/nanoid/cli.ts:18:13

    'read' is declared here.
        read(p: Uint8Array): Promise<number | null>;
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        at $asset$/lib.deno.ns.d.ts:219:5

TS2345 [ERROR]: Argument of type 'string | (() => string)' is not assignable to parameter of type 'string'.
  Type '() => string' is not assignable to type 'string'.
  log(id);
      ~~
    at https://deno.land/x/nanoid/cli.ts:48:7

Found 3 errors.

Add tests

Seems like a small typo can break the project #1

Tests could present regression like this.

https://deno.land/x/nanoid not available

the package is now invalid.
When I try to import it, is returning
No uploaded versions This module name has been reserved for a repository, but no versions have been uploaded yet. Modules that do not upload a version within 30 days of registration will be removed. If you are the owner of this module, please re-add the GitHub repository with deno.land/x (by following the instructions at https://deno.land/x#add), and publish a new version.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.