Explain Codes LogoExplain Codes Logo

How to generate unique ID with Node.js

javascript
prompt-engineering
best-practices
performance
Anton ShumikhinbyAnton Shumikhin·Jan 3, 2025
TLDR

For a shot of instant gratification, use uuid. To install, simply run npm install uuid, then:

const { v4: uuidv4 } = require('uuid'); console.log(uuidv4()); // Prints a UUID, like '123e4567-e89b-12d3-a456-426614174000'. Poof! Magic, ain't it?

Other tools in your arsenal

In-built uniqueness: Crypto.randomUUID()

Starting from Node v14.17.0, the crypto module provides crypto.randomUUID(), a way to create unique IDs without any third-party dependencies. Now that's what you call self-reliance:

const { randomUUID } = require('crypto'); console.log(randomUUID()); // example 'd94f3c65-0c8d-481e-bdec-a857444cd5b6'. No packages were harmed in the making of this ID!

The tiny powerhouse: Nanoid

When your IDs need to go on a diet, nanoid is your go-to choice. It gives you tiny, URL-friendly unique IDs:

const { nanoid } = require('nanoid'); console.log(nanoid()); // example 'V1StGXR8_Z5jdHi6B-myT'. Now fitting into skinny jeans!

Wrestling with uniqueness

Keeping it unique across the globe

In a scenario where your application is running in distributed systems and uniqueness is a necessity, opting for UUID v4 or v6 will offer the best randomness.

Database talks

IDs are often stored in a database, keep in mind the implications on storage requirements and indexing performance when using UUIDs.

Dealing with the old

Be mindful of deprecation notices. For instance, the shortid package has been deprecated. It's always recommended to use up-to-date libraries, and this is what nanoid or the built-in methods offer.

Exploring edge cases

Collision course

Keep in mind the probability of collisions when generating IDs. Small, but non-zero!

Running down the time

Combining timestamps with Date.now() and Math.random() offers a simple, albeit not fully unique, method:

const uniqueTimestampID = `timestamp-${Date.now()}-${Math.random()}`; console.log(uniqueTimestampID); // example 'timestamp-1617753298306-0.5045433645131588'. Now this is truly a moment in time!

Superpower: Crypto.randomBytes()

The crypto.randomBytes() method grants us a higher loot drop rate by controlling the *randomness factor:

const { randomBytes } = require('crypto'); const uniqueID = randomBytes(16).toString('hex'); console.log(uniqueID); // example 'e83b2aee311f4fdf8f024bff64739aca'. Yup, these bytes are truly out of the byte-box!