DEV Community

Cover image for Codebytes: Shorter UUIDs with collision prediction using nanoid
prakash chokalingam
prakash chokalingam

Posted on

Codebytes: Shorter UUIDs with collision prediction using nanoid

To generate an unique ID most of us use npm libraries and node utils like uuid, crypto.randomUUID. One of the major cons is these IDs are larger in size and the shorter UUID generation will increase the probability of duplicate IDs.

Here comes the saviour, nanoid - A tiny, secure, URL-friendly, unique string ID generator for JavaScript.

Since the bigger alphabet is being used in the UUID generation, nanoid can generate random unique ids within 21 chars.

And its 2x faster and safer than other UUID generators.

Wait... This will blow your mind!

mind blown

Nanoid is completely configurable from size to char's, to be used while generating the UUIDs. Then how does it avoid the probability of duplication? It comes with a collision calculator which helps to predict the probability of collision based on configuration.
collision calculator

It has support for various other programming languages. Checkout this awesome repo:

GitHub logo ai / nanoid

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

Nano ID

Nano ID logo by Anton Lovchikov

English | Русский | 简体中文

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 19 programming languages.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Enter fullscreen mode Exit fullscreen mode

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

Sponsored by Evil Martians

Table of Contents

Discussion (0)