How to generate unique ID with Node.js
For a shot of instant gratification, use uuid
. To install, simply run npm install uuid
, then:
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:
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:
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:
Superpower: Crypto.randomBytes()
The crypto.randomBytes()
method grants us a higher loot drop rate by controlling the *randomness factor:
Was this article helpful?