DEV Community

Utilgo Net
Utilgo Net

Posted on

UUID v4 Explained: How to Generate Unique Identifiers Safely in JavaScript

Unique identifiers play an important role in software development.

Applications need to identify users, database records, uploaded files, background jobs, API requests, and distributed events.

For small systems, sequential numeric IDs may be sufficient.

But distributed applications often benefit from identifiers that can be generated independently, without requesting the next value from a centralized database.

One widely used solution is UUID.

In this article, we'll explore what UUIDs are, how UUID version 4 works, how to generate them securely in JavaScript, and when they should—or shouldn't—be used.

1. What Is a UUID?

UUID stands for Universally Unique Identifier.

A UUID is a 128-bit value commonly displayed as 32 hexadecimal digits separated into five groups.

For example:

550e8400-e29b-41d4-a716-446655440000
Enter fullscreen mode Exit fullscreen mode

The familiar textual representation follows this structure:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

UUIDs are used to identify objects without requiring every system to coordinate with one central identifier generator.

This makes them particularly useful in distributed systems.

2. Understanding UUID Version 4

UUID version 4 uses random data to generate identifiers.

Some bits are reserved for version and variant information, leaving 122 random bits in a standard UUID v4.

This provides an extremely large space of possible identifiers.

The probability of accidentally generating the same UUID twice is very small when a suitable cryptographically secure random number generator is used.

However, UUIDs do not offer an absolute mathematical guarantee that collisions can never occur.

Applications should still enforce uniqueness where necessary.

For example, a database primary key or unique constraint remains important.

3. Generate UUID v4 in Modern JavaScript

Modern browsers provide the Web Crypto API.

You can generate a UUID v4 using:

const id = crypto.randomUUID();

console.log(id);
Enter fullscreen mode Exit fullscreen mode

This generates an identifier using a cryptographically secure random source.

crypto.randomUUID() is available in modern browser secure contexts and supported Node.js environments.

It is a much better option than manually constructing identifiers using Math.random().

4. Why Math.random() Is Not Recommended

You may encounter examples that generate identifiers by replacing characters in a template using Math.random().

Although such snippets may look convenient, Math.random() is not designed to provide cryptographically secure randomness.

Avoid using it to generate identifiers that depend on unpredictability.

Prefer standard cryptographic APIs.

For example, in Node.js:

import { randomUUID } from "node:crypto";

const userId = randomUUID();

console.log(userId);
Enter fullscreen mode Exit fullscreen mode

Using built-in cryptographic functionality avoids unnecessary custom implementation.

5. Practical Use Case: Database Records

Imagine building an application where users can create projects.

Each project requires an identifier.

function createProject(name) {
  return {
    id: crypto.randomUUID(),
    name,
    createdAt: new Date().toISOString()
  };
}

const project = createProject("New Dashboard");

console.log(project);
Enter fullscreen mode Exit fullscreen mode

The project receives an identifier without contacting a centralized ID-generation service.

In production, the database should still enforce uniqueness.

UUID values can also be generated on the backend, depending on your architecture and trust boundaries.

6. Practical Use Case: File Uploads

Uploaded files sometimes share the same filename.

Imagine two users uploading:

invoice.pdf
Enter fullscreen mode Exit fullscreen mode

Saving both files under their original names could cause collisions.

One possible approach is to assign an independent internal identifier:

const fileId = crypto.randomUUID();

const storedFilename = `${fileId}.pdf`;
Enter fullscreen mode Exit fullscreen mode

The original filename can be stored separately as metadata.

This improves filename uniqueness, but it does not replace file validation, access controls, path safety, malware scanning, or secure storage practices.

7. Practical Use Case: Request Tracing

Distributed applications often need to track a request across multiple services.

A request identifier can help correlate logs.

For example:

const requestId = crypto.randomUUID();

console.log({
  requestId,
  event: "order.created",
  status: "success"
});
Enter fullscreen mode Exit fullscreen mode

A consistent request ID makes it easier to connect events across services.

In larger systems, distributed tracing standards may provide additional context through trace and span identifiers.

8. UUID vs. Auto-Increment IDs

Both approaches have advantages.

Auto-increment IDs:

  • Compact and easy to read
  • Convenient for sequential database records
  • Often efficient for indexed storage
  • Usually require coordination for global uniqueness

UUID v4:

  • Can be generated independently
  • Useful across distributed services
  • Difficult to guess through simple enumeration
  • Requires more storage than small integer identifiers
  • Does not preserve creation order

Random UUIDs may also affect database index locality because their values are not sequential.

For workloads where chronological ordering is important, other identifier strategies may be worth evaluating.

9. UUIDs Are Not Authentication Tokens

A common mistake is assuming that a random-looking ID automatically provides security.

UUIDs are useful identifiers, but they should not replace authorization checks.

For example, a request to access:

/api/orders/550e8400-e29b-41d4-a716-446655440000
Enter fullscreen mode Exit fullscreen mode

must still verify that the authenticated user has permission to access that order.

Similarly, a UUID should not automatically be treated as a purpose-built secret token.

Use dedicated secure token-generation methods for credentials and security-sensitive workflows.

10. Generate UUIDs Without Writing Code

Sometimes developers need a temporary identifier for testing an API, preparing mock data, or checking database behavior.

Instead of opening a console, a browser-based UUID generator can provide a convenient alternative.

Utilgo's developer toolkit includes a UUID v4 generator that uses the browser's cryptographic random number generator.

The identifier is generated locally without a server request.

This is useful for test data, development workflows, and quick experiments.

11. Best Practices

When using UUIDs in production applications:

  1. Choose the UUID version based on your requirements.
  2. Use cryptographically secure randomness for UUID v4.
  3. Enforce uniqueness at the database level.
  4. Validate identifier input when accepting external requests.
  5. Keep authorization independent from identifier secrecy.
  6. Consider database performance and index behavior.
  7. Avoid creating your own UUID algorithm without a compelling reason.

Final Thoughts

UUIDs provide a practical mechanism for identifying objects across independent systems.

UUID version 4 is especially convenient when you need randomly generated identifiers without centralized coordination.

Modern JavaScript makes generation straightforward through crypto.randomUUID().

For quick testing, you can explore the free UUID Generator on Utilgo.

Do you prefer UUIDs, sequential IDs, or another identifier strategy in your projects?

Share your experience in the comments.


Part of the Utilgo developer productivity series.

Top comments (0)