While tweeting something or sharing something over Linkedin requires a unique id to identify a particular post. On the daily basis, we need to store or retrieve data uniquely & generating random numbers is not a cool idea. So through the post, we will take a look at the most commonly used NPM packages which are used for generating unique Ids.
1οΈβ£ UUID - UUID is the most popular npm package used for generating unique Ids. The npm package supports node version 10, 12, 14, and 16 & also provides support for React Native & browsers. It also supports version 1, 3, 4, and 5.
The Package can be installed by the npm install uuid
command. It provides support for both ES6 and CommonJS syntax.
Using the ES6 module syntax -
import { v4 as uuidv4 } from 'uuid';
const userId=uuidv4();
console.log(userId); // β¨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
Using the CommonJS syntax -
const { v4: uuidv4 } = require('uuid');
const userId=uuidv4();
console.log(userId); // β¨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
- The Module also provides a bunch of methods & methods for versions, check out all of them here π Github
2οΈβ£ Nano ID - Nano ID is very popular, tiny, URL-friendly & 2 times faster than uuid.
The package can be installed by npm install --save nanoid
command. Like uuid, it also provides support for both ES6 and CommonJS syntax.
Let's see an example through ES6 syntax -
import { nanoid } from 'nanoid'
const userId=nanoid();
console.log(userId); // => "V1StGXR8_Z5jdHi6B-myT"
- Suppose, if we need to reduce the id size to 10, then we can pass size as an argument like this -
nanoid(10) //=> "IRFa-VaY2b"
3οΈβ£ Cuid -
Install using the command
npm i cuid
Provides support for both ES6 and CommonJS syntax.
Example(using ES module syntax) -
import cuid from 'cuid';
console.log( cuid() );
// cjld2cjxh0000qzrmn831i7rn
4οΈβ£ crypto-random-string - It generates cryptographically strong random string.
- Works in Node.js and browsers.
- Install using the command
npm install crypto-random-string
- Example -
import cryptoRandomString from 'crypto-random-string';
cryptoRandomString({length: 10});
//=> '2cf05d94db'
- It also supports a second argument type(optional) along with length. The Default value for the type is hex.
5οΈβ£ uniqid -
- Install using the command
npm install uniqid
. - Unique Hexatridecimal ID generator.
- Creates unique IDs based on the current time, process, and machine name.
- Works in Node.js and browsers.
import uniqid from 'uniqid';
console.log(uniqid()); // -> 4n5pxq24kpiob12og9
π We have discussed the npm packages which are used for generating unique IDs. If you use a different package feel free to mention it in the comments.
Top comments (1)
Which one do you use or a different package ?