What is Nano ID & its difference from UUID as unique identifiers?

An overview of Nano ID

Every developer knows and uses unique identifiers in their works. It might be used as a primary key in a database, a credential key or a unique filename. One of the most popular identifiers, UUID, is generally applied by developers. But have you heard of a rising identifier these days named Nano ID? Is it more competitive and productive to be the new leading identifier for software development? In this article, you will have an in-depth sight of what is Nano ID, the difference between Nano ID vs UUID, and a detailed guide on creating a Nano ID generator API. Read on!

What is Nano ID in Node.JS and how does it work?

NanoID is a tiny, secure, URL-friendly, unique string ID generator for JavaScript. Although it is not as well-known as UUID, it has recently expanded quite quickly and appears to have great potential in being the leading identifier in the future. 

Nano ID uses URL-friendly symbols (A-Za-z0-9_-) by default and returns an ID with 21 characters (to have a collision probability similar to UUID v4).

Nano ID vs UUID – Major differences

The table below shows the major differences between Nano ID vs UUID:

Nano ID UUID
Browser supportSupports modern browsers e.g. React Native and Node.js  Supports for all major browsers
DependenciesNoneNone
Length of21 characters (using a larger alphabet than UUID(A-Za-z0-9_-). So ID size was reduced from 36 to 21 symbols)36 characters
LicenceMIT LicenceApache Licence 2.0
Number of portable languages20 programming languagesCommonJS, ECMAScript Modules and CDN builds
Number of random bits126 122
Package Size130 bytes483 bytes
Popularity in developer community18.2k starts on Github11.6k starts on Github
SecuritySafe (using a hardware random generator)Secure and well documented
SizeVery small in size (130 bytes) Small in size (483 bytes)
Speed2 times faster than UUID (due to memory allocation)2 times slower than Nano ID (due to memory allocation)

See the reference from github.com/ai/nanoid

Benefits of using Nano ID

From the difference versus UUID and others, we can summarise some major benefits of using Nano ID.

  • Shorter than a UUID
  • Easy to select with double clicking
  • Low chance of collisions
  • Easy to generate in multiple programming languages

Is Nano ID unique?

Nano ID is a unique string ID generator for JavaScript and other languages. As any other ID generator does, Nano ID has a certain probability of generating the identical ID twice, i.e. encountering a collision.

Referring to the Nano ID Collision Calculator, for example for a 12 character long Nano ID, It would require 1000 years to have 1% probability of at least one collision! With Nano ID, collision is not something we should worry about.

Benchmark

The benchmark showing Nano ID over other identifiers:

$ 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

See the reference from github.com/ai/nanoid

Installation

npm install --save nanoid

What is an API?

We all know that there are somethings we just don’t want do it manually. That’s where APIs come in. An API, or application programming interface, is a set of rules and specifications that allow two software programs to communicate with each other. Developers can build applications that work seamlessly together and make it possible for end-users to complete complex tasks with just a few clicks. By using an API, you can save yourself time and effort of having to write your own code from scratch. Let’s take a closer look at what an API is and how you can use it in your own development projects. If you want to know more about what an API is, check this link out.

For example, imagine being able to book a flight, hotel, and rental car all in one place by using just a few taps on your smartphone. This would not be possible without APIs! As the world becomes increasingly interconnected, the importance of well-designed APIs will only continue to grow.

Create your own Nano ID generator API

An alternative option for generating a Nano ID for quick use and with custom functionality would be using a Nano ID generator API. The sample API demonstrated here allows you to input your desired size and alphabet.

Why should you choose this server?

The Nano ID Generator API is supported by FabriXAPI, an All-in-one API Platform that supports API Needs and it is certified as “AWS Qualified Software” since 2022. You can register for an API portal for free, share and monetise APIs easily on the trustable platform certified by ISO27001.

Prerequisite

Before using this sample Nano ID generator API, there are some facts you have to learn of:

  • customAlphabet and customSize allows you to create Nano ID with your own alphabet and ID size.
  • Alphabet must contain 256 symbols or less. Otherwise, the security of the internal generator algorithm is not guaranteed.

You will need a suitable API provider. Using Dev Geeks’ Nano ID API supported by FabriXAPI, you can proceed easily as follows :

1. Sign up for a Developer Account

You need to sign up to the API Portal in order to subscribe and access this API. For more information, please refer to “Register as a Developer“.

2. Active API Subscription

You need to subscribe to this API before consuming it. Many APIs come with a free trial plan so that you can experience the API functions provided free of charge. For more information, please refer to “Subscribe to APIs“.

3. API Credential

An API Key is required to access the API. It can be obtained in the Developer Admin Portal once you have completed the signup to FabriXAPI. For more information, please refer to “Create API Key“.

You may check out the full API documentation here on the API Portal

UI Design of the API

Let’s get started from the User Interface. It’s hard to use or attract more users if your API do not have an easy-to-use user interface. Follow the below HTML to create a backbone of your UI. 

a sample UI
<div id="app">
  <div class="demo-description">
    <h2>Nano ID</h2>
    <span>To protect your credentials.</span>
    <br>
    <span>DO NOT save this API Key in the code sandbox!!</span>
  </div>
  <div class="test-area">
    <div class="input-area">
      <span>API Key</span>
      <input
        type="text"
        placeholder="Input your key here"
        v-model="apikey"
      >
      <br>
 
      <span>Custom Size</span>
      <input
        type="text"
        placeholder="Custom Size"
        v-model="size"
      >
      <br>
      <span>Custom Alphabet</span>
      <input
        type="text"
        placeholder="Custom Alphabet"
        v-model="alphabet"
      >
      <br>
      <button v-on:click="generate">Generate</button>
    </div>
 
    <div class="output-area">
      <template v-if="error">
        <span v-html="error" />
      </template>
      <template v-else-if="!result">
        Fill in the API Key, Custom Size and Custom Alphabet, then press "Generate".
      </template>
      <template v-else>
        <div v-html="result" />
      </template>
    </div>
  </div>
</div>

Add the below CSS to make your UI more engaging. 

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap');
body {
  background: #20262E;
  padding: 20px;
  font-family: 'Open Sans', sans-serif;
}
  
#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  /* height: 400px; */
}
  
.demo-description {
  text-align: center;
  margin-bottom: 20px;
}
  
.demo-description h2 {
  font-weight: semibold;
  margin-bottom: 5px;
}
  
.demo-description span {
  color: #999999;
}
  
.test-area {
  display: flex;
}
  
.input-area {
  text-align: right;
}
  
.input-area span {
  display: inline-block;
  line-height: 48px;
  margin-right: 8px;
  text-align: right;
  width: 150px;
}
  
.input-area input, select {
  border: 1px solid #999999;
  border-radius: 3px;
  height: 30px;
  width: 150px;
  padding: 0 7px;
}
 
.input-area select {
  height: 32px;
  width: 166px;
}
  
.input-area input::placeholder {
  color: #d0d0d0;
}
  
.input-area button {
  background-color: #57abf0;
  border: 0;
  border-radius: 4px;
  color: #ffffff;
  font-weight: 600;
  margin-top: 15px;
  width: 166px;
  padding: 15px 10px;
}
  
.output-area {
  color: #505050;
  font-size: 14px;
  margin: 20px;
  margin-right: 0px;
  width: calc(100% - 350px);
}
  
@media screen and (max-width: 616px) {
  .input-area {
    text-align: center;
  }
 
  .input-area span {
    text-align: left;
  }
    
  .output-area {
    width: calc(100% - 150px);
  }
    
  .input-area button {
    width: 140px;
    padding: 10px 7px;
  }
}
  
.output-area svg {
  transform: scale(0.7) translateX(-30px) translateY(-95px);
}

Implement the API with Vue.js

Now, you can add the following Vue.js script to generate the Nano ID.

const endpoint = 'https://trial-api-nanoid-519a.gw.openapihub.com/nanoid';
 
new Vue({
    el: '#app',
    data() {
    return {
        apikey: '',
      size: '',
      alphabet: '',
      result: '',
      error: ''
    }
  },
  methods: {
    generate: function() {
      const axiosConfig = {
        'content-type': 'application/json',
        'x-openapihub-key': this.apikey
      }
       
      const params = {
        'customSize': this.size,
        'customAlphabet': this.alphabet
      }
     
    axios.get(`${endpoint}`, { params: params, headers: axiosConfig })
        .then(res => {
        this.error = ''
        this.result = `Result -<br>${res.data}`
      }).catch(err => {
          this.error = `Error occurred -<br>${err.response.data.message}`
          console.log('Error', err.response.data.message)
      })
    }
  }
})

Generate your first Nano ID with your custom API

Now that we have all the materials prepared. Let’s take a look at creating our first Nano ID with our generator. 

Simply fill in the form with an API Key, Custom Size and Custom Alphabet, then press “Generate”. The API would swiftly return the Nano ID as a result.

And the output is as follows:
sample Nano ID generated
An output of random Nano ID generated in the middle.

Conclusion

NanoID is gradually becoming the leading unique id generator for JavaScript on the market. Most developer communities tend to prefer to use it over UUID considering its more outstanding performance in different aspects like faster speed, greater alphabet and smaller-sized package. Here, we showcase the advantage of using Nano ID and the easiest method to create your custom Nano ID generator API to facilitate your coming projects, business and products. So, start working with the new technology today!

Next Steps?

Enjoyed the above tutorial and want to start managing your own APIs? Let’s try our award-winning API platform – FabriXAPI for free! FabriXAPI is an all-in-one API management platform that allows you to create your own API portal, build API Collections, define subscriptions, and monetize your APIs. Take your API sharing to the next level with FabriXAPI and unlock new opportunities for API collaboration and growth. 

Join Our Community of API & AI Innovators!

Subscribe to OpenAPIHub e-newsletter for exclusive API & AI insights delivered straight to your inbox.

Discover more from OpenAPIHub Community

Subscribe now to keep reading and get access to the full archive.

Continue reading