DEV Community

Cover image for 4 packages to generate UUIDs in JavaScript
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

4 packages to generate UUIDs in JavaScript

Generating UUIDs

UUIDs are Universally Unique Identifiers. They are also known as GUIDs (Globally Unique Identifier). It is basically unique IDs. Below is an example

00630208-fe51-11eb-9a03-0242ac130003
Enter fullscreen mode Exit fullscreen mode

Let's take a look at 4 different ways to generate UUIDs in JavaScript

UUID 11.4k+⭐️

First, we will need to install it

npm install uuid
Enter fullscreen mode Exit fullscreen mode

Below is the code-snippet to generate an UUID

const uuid = require('uuid')

// Generates a version 4 uuid
console.log(
  uuid.v4()
)
// 01a8fc1c-81ff-4337-82af-c4bc64121851

// Generates a version 1 uuid
console.log(
  uuid.v1()
)
// 01a8fc1c-81ff-4337-82af-c4bc64121851
Enter fullscreen mode Exit fullscreen mode

NanoID 13.7k+ ⭐️

This is useful to generate URL friendly UUIDS.
Let's install the package

npm install nanoid
Enter fullscreen mode Exit fullscreen mode

Below is the code snippet

const nanoid = require('nanoid')

// Generate a random UUID
console.log(
  nanoid.nanoid(size = 32)
)
// QbM9RUrdJTfQjhRb_lK3oP0hPaqdmoMz

// Generate an uuid using specific characters
console.log(
  nanoid.customAlphabet('abcd#',32)()
)
// b#bdacc#dd#acdcdccacd#bd#bdacddd
Enter fullscreen mode Exit fullscreen mode

Short-UUID 239 ⭐️

To install the package

npm install short-uuid
Enter fullscreen mode Exit fullscreen mode

Below is the code snippet

const shortUUID = require('short-uuid')

// Generate an UUID
console.log(
  shortUUID.generate()
)
// 1B8f2uLpYVj454zycCjLB1

// Generate an UUID using specific characters
console.log(
  shortUUID(
    'b$a#c.*9'
  ).generate()
)
//$9c$.b$*b*#$*$ca$$c##9$c.a9.*9#$a..b*b##c#c
Enter fullscreen mode Exit fullscreen mode

UUIDV4 110 ⭐️

Install it

npm install uuidv4
Enter fullscreen mode Exit fullscreen mode

Below is the code snippet

const uuidv4 = require('uuidv4')

console.log(
  uuidv4.uuid()
)
// 67bf5875-cda6-45a7-bd2b-c5142956b786
Enter fullscreen mode Exit fullscreen mode

Top comments (0)