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.”
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.
The 128-bit UUID value is typically represented as a 36-character string when including hyphens, or 32 characters without hyphens. The standard format consists of 32 hexadecimal characters grouped into five sections, separated by hyphens. Here’s an example:
550e8400-e29b-41d4-a716-446655440000
(36 characters)550e8400e29b41d4a716446655440000
(32 characters)The length of a UUID is directly tied to its uniqueness. A 128-bit UUID provides 2^128 (approximately 3.4 x 10^38) possible unique values, making the probability of a collision (two UUIDs being the same) extremely low. For example, if you generate 1 billion UUIDs per second, it would take 86 years to reach a 50% chance of a 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 several purposes. Shortening UUIDs comes with tradeoffs, which this article will also discuss.
Editor’s note: This article was last updated by Ikeh Akinyemi in March 2025.
Generating UUIDs in Node.js is a common task, especially in distributed systems, databases, and applications requiring high levels of uniqueness. However, there are multiple ways to generate UUIDs in Node.js, each with its own strengths and weaknesses. In this section, we’ll compare four popular methods for generating UUIDs:
uuid
npm packagecrypto.randomUUID()
methodMath.random()
for custom UUID generationBy the end of this section, you’ll have a clear understanding of which method is best suited for your specific use case.
uuid
npm packageThe uuid
package is one of the most popular libraries for generating UUIDs in Node.js. It supports multiple UUID versions (v1 to v6) and provides a simple API for generating cryptographically secure UUIDs:
npm install uuid
import { v4 as uuidv4 } from 'uuid'; const uuid = uuidv4(); console.log(uuid); // Example output: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
The uuid
package is ideal for projects that require support for multiple UUID versions (v1, v3, v4, v5, and v6) or need advanced features like UUID validation and custom formatting. If your application demands flexibility and cross-platform compatibility, this package is a strong choice.
Buffer
crypto.randomUUID()
methodNode.js introduced the crypto.randomUUID()
method in version 14.17.0, providing a built-in way to generate UUIDs without external dependencies. The crypto.randomUUID()
method generates a UUID v4, which is a randomly generated 128-bit identifier.
Unlike other UUID versions (e.g., v1, which includes a timestamp and MAC address), UUID v4 is entirely random, making it ideal for most use cases where uniqueness and security are paramount:
import crypto from 'node:crypto'; const uuid = crypto.randomUUID(); console.log(uuid); // Example output: '550e8400-e29b-41d4-a716-446655440000'
The built-in crypto.randomUUID()
method is perfect for developers who want a simple, secure, and dependency-free way to generate UUID v4 identifiers. If your application only requires UUID v4 and doesn’t need advanced customization, this method is an excellent choice.
uuid
packageMath.random()
for custom UUID generationWhile not recommended for most use cases, you can generate UUIDs using Math.random()
for simple, non-cryptographic purposes. This method is generally less secure and should be used with caution:
function generateCustomUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } const uuid = generateCustomUUID(); console.log(uuid); // Example output: 'e4e3f8d0-4b2d-4b5d-9b5d-ab8dfbbd4bed'
Using Math.random()
for UUID generation is best suited for non-critical, internal use cases where security is not a priority. If you need a quick and lightweight solution for generating unique IDs without external dependencies, this approach can work, but it should be used with caution due to its lack of cryptographic security.
In addition to the traditional UUID generation methods, there are several alternative libraries that offer unique features for generating unique identifiers. These libraries are particularly useful when you need shorter IDs, enhanced security, or URL-friendly formats.
short-uuid
packageThe short-uuid
package allows you to generate and translate RFC 4122 v4-compliant UUIDs into shorter formats. This is particularly useful for applications where shorter IDs are preferred, such as in URLs or database storage:
npm install short-uuid
import short from 'short-uuid'; const translator = short(); const shortId = translator.generate(); console.log(shortId); // Example output: '2gYx5fZb' const originalUUID = translator.toUUID(shortId); console.log(originalUUID); // Converts back to the original UUID
The short-uuid
package is ideal for applications where compact IDs are beneficial; this package provides a great balance between readability and efficiency.
cuid2
packageThe cuid2
package is designed to generate secure, collision-resistant IDs that are URL-friendly and do not leak sensitive information. It is an enhanced version of the original cuid
package, with improved security features:
npm install @paralleldrive/cuid2
import { createId } from '@paralleldrive/cuid2'; const id = createId(); console.log(id); // Example output: 'hgyoie0b9qb1fyso09hjyoef'
The cuid2
package is a strong choice for where security and collision resistance are critical. If you need outputs that are highly unpredictable, cuid2
provides a secure and reliable solution.
nanoid
packageThe nanoid
package is a lightweight library for generating random, URL-friendly IDs. It is particularly popular for generating short IDs for use in URLs, verification codes, and database primary keys:
npm install nanoid
import { nanoid } from 'nanoid'; const id = nanoid(); console.log(id); // Example output: 'e4D3gvwajLcsYhdgOXK6B'
For advanced use cases, you can create custom UUIDs using hash functions like SHA-256. This approach allows you to generate UUIDs based on specific input data, ensuring uniqueness while maintaining control over the generation process:
import crypto from 'node:crypto'; function generateHashBasedUUID(input) { const hash = crypto.createHash('sha256').update(input).digest('hex'); return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`; } const uuid = generateHashBasedUUID('custom-input-data'); console.log(uuid); // Example output: '5a105e8b-9d5c-4b2d-9b5d-ab8dfbbd4bed'
Custom hash-based UUIDs are ideal for advanced use cases where you need deterministic UUIDs based on specific input data, providing flexibility where it is needed.
Method | UUID versions supported | Cryptographically secure | External dependency | Customization options | Use case highlights |
---|---|---|---|---|---|
uuid npm package |
v1, v3, v4, v5, v6 | âś… | âś… | High | Multiple UUID versions, validation |
crypto.randomUUID() |
v4 | ✅ | ❌ | Low | Built-in, no dependencies |
Math.random() |
Custom | ❌ | ❌ | Medium | Simple, non-secure use cases |
short-uuid |
v4 | âś… | âś… | Medium | Shorter IDs, URL-friendly |
cuid2 |
Custom | âś… | âś… | High | Secure, collision-resistant, URL-friendly |
nanoid |
Custom | âś… | âś… | High | Short, URL-friendly, lightweight |
Custom hash-based UUIDs | Custom | Depends on implementation | ❌ | High | Deterministic, input-based UUIDs |
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).
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 like 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 nowUse Flutter to build browser-based app demos that help clients visualize the product, speed up buy-in, and close deals faster.
TypeScript’s new Go-based compiler offers 10x faster builds, improved CI/CD performance, quicker editor startup, and enhanced hot reload times.
Learn how to manage JavaScript closures in React and explore real-life examples of proper JavaScript closure management.
By building these four simple projects, you’ll learn how CSS variables can help you write reusable, elegant code and streamline the way you build websites.