Editor’s note: This article was last updated by Amazing Enyichi Agu on 24 September 2024 to incorporate UUID alternative packages for generating secure and random IDs, including nanoid
and cuid2
.
A Universally Unique Identifier, or UUID, is a 128-bit value generated by a computer system that has extremely low chances of repeating. According to the Internet Engineering Task Force (IETF) in RFC 4122, the first official specification for implementing UUIDs in computer systems, UUID protocol is defined as “A 128-bits-long identifier that can guarantee uniqueness across space and time.”
Because generated UUIDs are so distinct from each other, they are used to uniquely identify database records, documents, programs, or whatever else that may need to be uniquely identified for efficient storage and retrieval.
Today, UUIDs are popular among developers because they are a reliable and convenient way to label data distinctly. There are also different versions of UUID that the IETF has released specs for. At the time of writing, the latest UUID version is v8.
According to UUID specs, the 128 bits that make up a UUID have different segments that serve different purposes. However, the segmentation and their purposes depend on the UUID version. For example, v1, v2, and v6 have a 48-bit segment representing the MAC address of the computer system that generated the UUID. They also have a 60-bit segment for a timestamp and a 13 or 14-bit segment for a “uniqifying” clock sequence. In another example, v4 UUIDs contain a 122-bit segment of randomly generated values.
More commonly, UUIDs are presented in a format that looks like this: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
. Here, x
is a hexadecimal value that represents four bits. A UUID is usually a string with an 8-4-4-4-12 format (32 hex values and four hyphens). Here is an example:
b592d358-adf0-4782-b90e-d8ee4118ddcd
Most operating systems have a CLI tool for generating UUIDs:
uuidgen // generates a UUID uuidgen help // view help for the UUID command.
The uuidgen
command is available on Windows, Linux, and macOS systems to generate UUIDs (mostly v4) on the command line or terminal.
You can use UUIDs in many areas of software development. For example, they can be used in distributed applications, databases, networking, and scenarios where a high degree of randomness is significant. This guide assumes most readers will use UUIDs to generate unique identifiers for data stored in a database.
The UUID protocol was designed to implement unique identifiers. UUID collisions occur when a program generates and assigns the same UUID to two or more entities (such as files or data).
Each UUID is almost always distinct from other existing UUIDs. Therefore, there is a very low chance of collision. Consider v4 UUIDs, for example, which are the most commonly used. If a program generated 100 billion v4 UUIDs in one second, it would take 86 years before there was a 50% chance of at least one collision.
UUID collisions are detrimental where identifiers have to be unique — for example, where the UUIDs are the primary keys in a database table.
As mentioned above, the standard length of generated UUIDs is 128 bits. However, you can shorten a UUID for a number of purposes. Shortening UUIDs comes with tradeoffs, which this article will also discuss.
This section will discuss three popular ways of generating UUIDs in Node.js: using the built-in crypto
module, the uuid
package, and the short-uuid
package.
crypto
moduleMost programming languages provide functionalities for generating UUIDs. In the Node runtime, the built-in crypto
package has a randomUUID
method for generating them.
First, import the crypto
package into your JavaScript file:
const crypto = require('node:crypto'); // CommonJS // or import crypto from 'node:crypto'; // ES Modules
Calling the UUID method returns a UUID of standard length that you can use in your program:
let uuid = crypto.randomUUID(); console.log(uuid);
The code prints the generated UUID to the console:
The benefit of using the crypto
module in Node is that you do not need to install any external dependency. Generating a UUID with crypto
is also straightforward, as the above example shows. However, the crypto
module only allows you to generate v4 UUIDs. Also, there are limited configuration options for the UUIDs compared to using the uuid
package.
uuid
packageThe uuid
package provides functionality for generating cryptographically secure, standard UUIDs with support for versions 1-6 UUIDs, as well as cross-platform support for Node, CommonJS, webpack, React Native Expo, and more.
The uuid
package is an external dependency, so you’ll have to install it to use it:
npm install uuid
After installing uuid
, import the package into your JavaScript file:
const uuid = require('uuid'); // CommonJS // or import uuid from 'uuid'; // ES Modules
Here’s an example of generating a v4 UUID with uuid
:
const uuid4 = uuid.v4() console.log(uuid4)
The v4
method returns v4 UUIDs, and the code prints the UUID to the console:
Using this module, a developer can generate different versions of UUID (v1, v3-v6). The library also has better customization options for the IDs. For example, in v1, you can set the value of milliseconds used when generating the ID. You can also set the UUID to return as a Buffer
data type instead of the typical string value.
This library has many extra features, such as validating UUIDs, and is straightforward to use. These benefits come with the tradeoff of having to add an extra dependency to your Node.js project.
short-uuid
packageThe short-uuid
package provides functionalities for generating and translating RFC 4122 v4-compliant standard UUIDs into shorter formats and vice versa. You can use the short-uuid
package to generate v4 UUIDs and shorten them for your application’s use cases.
The short-uuid
package is secure, with features like errors on incorrect UUIDs. By default, short-uuid
returns shortened IDs of a consistent length, except if you specify a length, and the package shortens UUIDs by padding the alphabet characters.
Run this command in the terminal of your working directory to install the short-uuid
package:
npm install short-uuid
After installing short-uuid
, you can import the package into your app:
const short = require('short-uuid'); // CommonJS // or import short from 'short-uuid' // ES Modules
You can generate a simple, long UUID with the uuid
method of your short-uuid
instance:
console.log(short.uuid());
The uuid
method returns a UUID with a standard length of 128 bits. You can generate shorter UUIDs with the generate
method, which returns a Flickr base58
format by default:
base58 = short.generate() console.log(base58);
You can add additional arguments to your short-uuid
package instance for extra functionalities. Adding distinct values will yield padded formats of the UUIDs:
// must not be duplicated const translator = short("32814"); // Provide a specific alphabet for translation const uuid = translator.generate() console.log(uuid)
The function will throw an error if there are duplicates in the alphabet values.
Here’s how you can shorten UUIDs and retrieve the original values with the short-uuid
package:
const short = require('short-uuid'); const translator = short("342"); newUUID = translator.new() original = translator.fromUUID(newUUID); bits128 = translator.toUUID(original); console.log(newUUID) // prints the generated UUID console.log(original) // prints the original UUID console.log(bits128) // prints reverted UUID of 128bits
You generated a new UUID with the new
method, an alias for the generate
method that returns a padded UUID. The newUUID
variable is the padded UUID generated by short-uuid
, and the fromUUID
method returns the original 128-bit UUID before padding. The toUUID
method returns the originally generated UUID with the package:
short-uuid
is flexible because it allows developers to generate both normal and shorter UUIDs. Shortened UUIDs are better for database storage because they take up less space. They also look better when used in URLs, as opposed to ones of standard length. As this section shows, short-uuid
also allows extensive customization of the IDs. With it, you can also generate shorter IDs in different bases, and convert them back.
However, short-uuid
and shortening UUIDs come with some limitations. First, short-uuid
only generates and shortens v4 UUIDs. This means you cannot use short-uuid
to generate other UUID versions. Also, it is an extra dependency on your Node.js project. Therefore, it should ideally only be used for projects that need short IDs and that follow the UUID v4 spec.
UUIDs are popular for identifying data stored in a database table and are often effective for this purpose. However, due to the way some database engines work or the anatomy of a UUID, they are not the best for every application or scenario. This section will cover some important drawbacks of using UUIDs in these contexts.
Some database engines like PostgreSQL, MySQL, and SQLite use the B+ tree data structure for indexing. If a developer implements UUIDs as a primary key, the database will likely spend more time re-balancing the B+ tree index whenever an insertion occurs. This is because generated UUIDs are not sequential (compared to incremental integers, for example). B+ tree indexes are better optimized for sequential IDs.
Using UUIDs can hurt performance and lead to slower writes in very large-scale databases. To combat this effect, alternative sequential IDs (e.g., incremental integers or Snowflake IDs) can be used instead.
In its essence, a UUID is just an encoded collection of data — like a timestamp, a random number, sometimes a MAC address, etc. — that can be swiftly decoded to reveal its contents to malicious actors. By decoding a UUID, one can figure out when a database record was created, guess another valid ID, or reveal the MAC address of the computer that created the record.
There are two options for web applications that need to guard this kind of data. They either must make sure to never expose a UUID to the client (e.g., frontend, mobile app), or they use more secure ID generators that do not leak data (e.g., using the cuid2
or nanoid
package).
As discussed in the previous section, UUIDs have some flaws. Alternatives to UUIDs are available to improve unique ID generation for data in applications. This section will discuss two alternative packages to generate IDs: cuid2
and nanoid
.
cuid2
packagecuid2
is an enhanced version of the cuid
package — think of it like a really cool sequel. The original cuid
generated k-sorted, random IDs that are collision-resistant. However, the cuid
package is now deprecated mostly due to security concerns.
IDs from cuid2
are URL-friendly as they do not contain any special characters like asterisks, forward slashes, etc. They are also random and not sequentially generated. In fact, cuid2
hashes the data it uses to generate the ID. That way it is almost impossible to guess the next ID or learn anything about the data an ID references.
With cuid2
, a developer can customize an ID such as by, for example, setting its length. You can also check if a string is a valid cuid2
ID.
To use cuid2
, install the module using npm or the package manager of your choice:
npm install @paralleldrive/cuid2
Import createId
to create an ID with default customization options:
import { createId } from '@paralleldrive/cuid2'; const id = createId(); console.log(id); // hgyoie0b9qb1fyso09hjyoef
You can also customize the IDs by specifying the length, providing a random function that works similarly to Math.random
, and including a fingerprint option that identifies the host environment. For this, you need to import the init
function:
import { init } from '@paralleldrive/cuid2'; const createId = init({ random: Math.random, length: 12, fingerprint: 'tutorial pc', }); const ids = [createId(), createId(), createId()] console.log(ids); // [tvx5ix8vilw2, qx9r30gzkf8q, d2jo1qoa0bgb]
cuid2
IDs will work well for applications that need secure, collision-resistant IDs. IDs from cuid2
are not sequential so keep that in mind while using them as primary keys in large-scale databases.
Depending on the database engine and data scale, using cuid2
IDs as a primary key might slow down operations like insert
and delete
due to the large size of the IDs. However, cuid2
offers greater security and unpredictability than UUIDs, making it more suitable for applications that prioritize collision resistance and data protection.
nanoid
packagenanoid
is a popular library for generating random IDs in JavaScript applications. It works in both the Node.js runtime and the browser. nanoid
generates tiny and URL-friendly ID strings that can be used for a variety of purposes, including verification codes, database primary keys, identification, and more.
nanoid
is really tiny in size. According to Bundlephobia, when the package is gzipped and minified, it is still not up to 1 KB. Also, nanoid
IDs are not generated sequentially. It is also hard for collisions to occur. Interacting with this Nano ID Collision Calculator shows how strongly collision-resistant nanoid
IDs are.
To use this module, first install it in your project:
npm install nanoid
Import the nanoid
function and call it to generate an ID:
import { nanoid } from 'nanoid'; const id = nanoid(); console.log(id); // e4D3gvwajLcsYhdgOXK6B
You can set the length of the ID by passing an integer as an argument to the nanoid
function. For example, nanoid(12)
will generate an ID with a length of 12 characters. You can also generate IDs with custom alphabets and predefined lengths using the customAlphabet
function:
import { customAlphabet } from 'nanoid'; const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 6); // Here, 6 is the predefined length const id = nanoid(); console.log(id); // 1dk3iv
The nanoid
library has great customization options. Overall, it also generates shorter IDs, which can save database space as opposed to using typical UUIDs that have 36 characters. nanoid
also hashes data used to generate the ID, which makes it a lot more secure than encoded ID solutions like short-uuid
. However, remember that the downsides to non-sequential IDs as database primary keys apply here as well.
While UUIDs are a common choice for generating unique identifiers in Node.js applications, they aren’t always the best option for every scenario. Though UUIDs offer globally unique IDs, their potential for performance drawbacks, especially for applications that require enhanced security, can be a concern. Consider using UUID alternatives cuid2
and nanoid
, which provide more secure and unpredictable IDs that are less likely to leak sensitive information.
Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third-party services are successful, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.
LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowThe useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.
Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.
Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.
Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]