VOOZH about

URL: https://blog.logrocket.com/uuids-node-js/

⇱ Understanding UUIDs in Node.js - LogRocket Blog


2025-03-03
1992
#node
Ukeje Goodness
133724
πŸ‘ Image

See how LogRocket's Galileo AI surfaces the most severe issues for you

No signup required

Check it out

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.”

πŸ‘ Understanding UUIDs In Node.js

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.

πŸš€ Sign up for The Replay newsletter

The Replay is a weekly newsletter for dev and engineering leaders.

Delivered once a week, it's your curated guide to the most important conversations around frontend dev, emerging AI tools, and the state of modern software.

UUID length and collisions

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:

  • With hyphens: 550e8400-e29b-41d4-a716-446655440000 (36 characters)
  • Without hyphens: 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

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:

  • Using the uuid npm package
  • Using Node.js’s built-in crypto.randomUUID() method
  • Using Math.random() for custom UUID generation
  • Alternative approaches (e.g., custom hash-based UUIDs)

By the end of this section, you’ll have a clear understanding of which method is best suited for your specific use case.

1. Using the uuid npm package

The 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.

Pros:

  • Supports multiple UUID versions (v1, v3, v4, v5, v6)
  • Cross-platform compatibility (Node.js, browsers, React Native, etc.)
  • Additional features like UUID validation and conversion to Buffer

Cons:

  • Requires an external dependency
  • Slightly larger bundle size compared to using built-in methods

2. Using Node.js’s built-in crypto.randomUUID() method

Node.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.

Pros:

  • No external dependencies required
  • Simple and straightforward API
  • Cryptographically secure

Cons:

  • Only supports UUID v4
  • Limited customization options compared to the uuid package

3. Using Math.random() for custom UUID generation

While 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.


Over 200k developers use LogRocket to create better digital experiences

πŸ‘ Image
Learn more β†’

Pros:

  • No external dependencies
  • Simple to implement for basic use cases

Cons:

  • Not cryptographically secure
  • Higher risk of collisions compared to other methods

4. Alternative approaches

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.

a. Using the short-uuid package

The 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.

Pros:

  • Generates shorter, URL-friendly IDs
  • Allows conversion between short IDs and standard UUIDs
  • Supports custom alphabets for ID generation

Cons:

  • Only supports UUID v4
  • Adds an external dependency to your project

b. Using the cuid2 package

The 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.

Pros:

  • Generates secure, collision-resistant IDs
  • URL-friendly and does not contain special characters
  • Customizable ID length and generation options

Cons:

  • IDs are not sequential, which may impact database performance in large-scale applications
  • Adds an external dependency to your project

c. Using the nanoid package

The 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'

Pros:

  • Generates short, URL-friendly IDs
  • Highly collision-resistant
  • Extremely lightweight (less than 1 KB when minified and gzipped)

Cons:

  • IDs are not sequential, which may impact database performance in large-scale applications
  • Adds an external dependency to your project

d. Custom hash-based UUIDs:

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.

Pros:

  • Customizable based on input data
  • Can be used to generate deterministic UUIDs

Cons:

  • More complex to implement
  • Requires careful handling of input data to ensure uniqueness

Comparing UUID methods

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

Downsides to using UUIDs as database primary keys

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.

Database indexing

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.

Security concerns

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).

Conclusion

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.

200s only πŸ‘ Image
Monitor failed and slow network requests in production

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 Network Request Monitoring

LogRocket lets you replay user sessions, eliminating guesswork around why bugs happen by showing exactly what users experienced. It captures console logs, errors, network requests, and pixel-perfect DOM recordings β€” compatible with all frameworks.

LogRocket's Galileo AI watches sessions for you, instantly identifying and explaining user struggles with automated monitoring of your entire product experience.

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.

πŸ‘ Image
πŸ‘ Image
πŸ‘ Image

Stop guessing about your digital experience with LogRocket

Get started for free

Recent posts:

Stop hardcoding LLM SDKs: Dynamic LLM routing with OpenRouter and Next.js

Build dynamic LLM routing in Next.js with OpenRouter, TanStack AI, task classification, model fallbacks, and cost-aware routing.

πŸ‘ Image
Chizaram Ken
Jun 16, 2026 β‹… 13 min read

What is TSRX?: What JSX would look like if it were designed today

TSRX adds first-class control flow, conditional hooks, and scoped styles to React via a TypeScript compiler extension β€” no new framework required.

πŸ‘ Image
Ikeh Akinyemi
Jun 12, 2026 β‹… 6 min read

How to add authentication to a React Native app with Better Auth

Learn how to build a full React Native auth system using Better Auth and Expo β€” with email/password login, Google OAuth, session persistence, and protected routes.

πŸ‘ Image
Chinwike Maduabuchi
Jun 9, 2026 β‹… 13 min read

AI dev tool power rankings & comparison [June 2026]

Compare the top AI development tools and models of June 2026. View updated rankings, feature breakdowns, and find the best fit for you.

πŸ‘ Image
Chizaram Ken
Jun 8, 2026 β‹… 11 min read
View all posts

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 now