Generate UUID in Node.js (NodeJS UUID Generator Guide)

Generate UUID in Node.js (NodeJS UUID Generator Guide)

UUID (Universal Unique Identifier) is commonly used in Node.js applications to generate unique identifiers for database records, API requests, sessions, files, and distributed systems. Instead of relying on sequential IDs, developers often use UUIDs to ensure uniqueness across multiple servers and services.

Node.js provides several ways to generate UUIDs including the popular uuid npm package and the built-in crypto.randomUUID() method available in modern Node.js versions.


Node.js UUID Cheat Sheet

TaskCode ExampleNotes
Install UUID packagenpm install uuidMost commonly used library
Import UUID (CommonJS)const { v4: uuidv4 } = require('uuid')Works in older Node versions
Import UUID (ES Modules)import { v4 as uuidv4 } from 'uuid'Recommended for modern Node
Generate random UUIDuuidv4()Most common usage
Generate timestamp UUIDuuid.v1()Uses timestamp + MAC address
Generate namespace UUIDuuid.v5(name, namespace)Deterministic UUID
Built-in UUID generatorcrypto.randomUUID()No external package required
Validate UUIDuuid.validate(id)Returns true/false
Generate multiple UUIDsArray.from({length:5}, () => uuidv4())Batch generation
Generate UUID for file nameconst file = uuidv4()+'.jpg'Useful for uploads

Basic Example: Generate UUID in Node.js

javascript
import { v4 as uuidv4 } from 'uuid'

const id = uuidv4()
console.log(id)

Example output

3d594650-3436-4537-b7c1-19c1f7f4d7e4

Installing and Importing UUID Package in Node.js

The most common way to generate UUIDs in Node.js is by using the uuid npm package. This library provides multiple UUID generation methods such as v1, v3, v4, and v5. It is widely used in Node.js applications for generating unique identifiers for databases, APIs, and distributed systems.

Installing uuid package using npm

First install the UUID package using npm.

npm install uuid

Once installed, the package can be used in your Node.js application to generate UUID values.

Importing uuid in CommonJS modules

If your Node.js application uses CommonJS modules (default in many older projects), you can import the package using require.

javascript
const { v4: uuidv4 } = require('uuid')

const id = uuidv4()
console.log(id)

Example output

550e8400-e29b-41d4-a716-446655440000

Importing uuid in ES modules

Modern Node.js applications often use ES modules. In this case, you can import the UUID library using the import statement.

javascript
import { v4 as uuidv4 } from 'uuid'

const id = uuidv4()
console.log(id)

This syntax is recommended when your project uses "type": "module" in package.json.

Understanding UUID library exports

The uuid library exports multiple functions for generating and validating UUIDs.

Common exports include:

FunctionPurpose
v1()Timestamp-based UUID
v3()Namespace-based UUID using MD5
v4()Random UUID (most common)
v5()Namespace-based UUID using SHA-1
validate()Check if a string is a valid UUID
parse()Convert UUID string to byte array
stringify()Convert byte array to UUID string

Among these, UUID v4 is the most widely used because it generates random identifiers with a very low probability of collision.


Generating UUID in Node.js

Generate random UUID using uuid.v4()

UUID version 4 generates a completely random identifier. This is the most commonly used UUID version in modern applications.

javascript
import { v4 as uuidv4 } from 'uuid'

const id = uuidv4()
console.log(id)

Example output

9f1b1d2e-5e92-4a5a-9a88-2f1d89b6c8c3

This method is recommended when you simply need a unique identifier.

Generate timestamp-based UUID using uuid.v1()

UUID version 1 generates identifiers based on the current timestamp and the machine's MAC address.

javascript
import { v1 as uuidv1 } from 'uuid'

const id = uuidv1()
console.log(id)

Example output

6ba7b810-9dad-11d1-80b4-00c04fd430c8

This version is useful when identifiers need to be ordered by creation time.

Generate namespace-based UUID using uuid.v3()

UUID version 3 generates deterministic UUIDs based on a namespace and a name using the MD5 hashing algorithm.

javascript
import { v3 as uuidv3 } from 'uuid'

const id = uuidv3('example.com', uuidv3.DNS)
console.log(id)

The same input always generates the same UUID.

Generate namespace-based UUID using uuid.v5()

UUID version 5 works similarly to v3 but uses SHA-1 hashing, making it more secure.

javascript
import { v5 as uuidv5 } from 'uuid'

const id = uuidv5('example.com', uuidv5.DNS)
console.log(id)

Namespace UUIDs are useful when you need consistent identifiers for the same input value.


Using Built-in UUID Generation in Modern Node.js

Generating UUID using crypto.randomUUID()

The crypto.randomUUID() method generates a random UUID using a cryptographically secure algorithm.

javascript
const { randomUUID } = require('crypto')

const id = randomUUID()
console.log(id)

Example output

3b12f1df-5232-4804-897e-917bf397618a

This method is available in Node.js 14.17+ and newer versions.

Differences between uuid.v4 and crypto.randomUUID

Featureuuid.v4crypto.randomUUID
Requires npm packageYesNo
Built into Node.jsNoYes
UUID versionv4v4
Cryptographically secureYesYes
Recommended for modern Node.jsOptionalYes

If you only need random UUID generation, crypto.randomUUID() is often the simplest solution.

Performance comparison of built-in vs external library

The built-in crypto.randomUUID() method typically performs slightly faster because it avoids loading external dependencies.

However, the uuid package offers additional features such as:

  • namespace UUID generation
  • UUID validation
  • UUID parsing and formatting

For most applications, the performance difference is minimal.

When to prefer built-in UUID generation

You should prefer crypto.randomUUID() when:

  • You only need UUID v4
  • You want to avoid installing external dependencies
  • Your application runs on modern Node.js versions

The uuid package is still useful when you need:

  • namespace UUIDs (v3 or v5)
  • timestamp UUIDs (v1)
  • UUID validation and parsing utilities

Generating Unique IDs for Database Records

UUIDs are frequently used as unique identifiers for database records. Unlike auto-increment IDs, UUIDs allow distributed systems to generate unique values without relying on a central database sequence.

Assigning UUID as primary keys

You can generate a UUID before inserting a record and use it as the primary key.

javascript
import { v4 as uuidv4 } from 'uuid'

const user = {
  id: uuidv4(),
  username: "john",
  email: "john@example.com"
}

console.log(user)

Example output

{
  id: 'a5c6d78e-48c0-4d8c-b27f-2f3e0e4e8f19',
  username: 'john',
  email: 'john@example.com'
}

Using UUIDs prevents ID collisions when multiple services insert records simultaneously.

Generating UUID before inserting into database

In many applications, a UUID is generated in the application layer before inserting data into the database.

javascript
import { v4 as uuidv4 } from 'uuid'

function createOrder(orderData) {
  return {
    orderId: uuidv4(),
    ...orderData
  }
}

const order = createOrder({ product: "Laptop", price: 900 })
console.log(order)

This ensures every record has a globally unique identifier.

Using UUID for MongoDB documents

MongoDB automatically creates an _id field, but you can use UUIDs for custom identifiers.

javascript
import { v4 as uuidv4 } from 'uuid'

const product = {
  productId: uuidv4(),
  name: "Keyboard",
  price: 45
}

db.products.insertOne(product)

This approach is useful when integrating with other services that expect UUID-based identifiers.

Using UUID for relational database tables

UUIDs are commonly used as primary keys in relational databases such as PostgreSQL or MySQL.

javascript
import { v4 as uuidv4 } from 'uuid'

const userId = uuidv4()

const query = `
INSERT INTO users (id, username, email)
VALUES ('${userId}', 'alice', 'alice@example.com')
`

Relational databases often store UUIDs as CHAR(36) or UUID data types.


Creating Unique Identifiers for APIs

Generating request IDs for API tracking

A request ID can be attached to every incoming API request for debugging and logging.

javascript
import { v4 as uuidv4 } from 'uuid'

app.use((req, res, next) => {
  req.requestId = uuidv4()
  console.log("Request ID:", req.requestId)
  next()
})

This allows developers to trace requests through logs.

Creating correlation IDs for microservices

In microservice architectures, correlation IDs help track requests across multiple services.

javascript
import { v4 as uuidv4 } from 'uuid'

const correlationId = uuidv4()

fetch("http://service-b/api", {
  headers: {
    "x-correlation-id": correlationId
  }
})

Each service can log the same correlation ID for easier debugging.

Using UUID for API tokens

UUIDs can be used as simple API keys or temporary access tokens.

javascript
import { v4 as uuidv4 } from 'uuid'

const apiToken = uuidv4()
console.log("Generated API token:", apiToken)

These tokens can then be stored and validated during API authentication.

Tracking requests across distributed systems

Large distributed systems often rely on UUIDs to track transactions across services.

javascript
import { v4 as uuidv4 } from 'uuid'

const transactionId = uuidv4()

console.log("Transaction ID:", transactionId)

This identifier can appear in logs across multiple services.


Generating Unique IDs for Files and Resources

Creating unique file names

UUIDs can be used as part of file names to ensure uniqueness.

javascript
import { v4 as uuidv4 } from 'uuid'

const filename = `${uuidv4()}.txt`
console.log(filename)

Example output

4e6c2a3e-9c1a-4e28-bff0-dc60f7e64e71.txt

Generating UUID for uploaded files

When handling file uploads, UUIDs prevent duplicate file names.

javascript
import { v4 as uuidv4 } from 'uuid'

const uploadedFile = {
  originalName: "photo.jpg",
  storedName: `${uuidv4()}-photo.jpg`
}

console.log(uploadedFile)

Creating unique temporary files

Temporary files generated during processing can use UUIDs.

javascript
import { v4 as uuidv4 } from 'uuid'

const tempFile = `/tmp/${uuidv4()}.tmp`
console.log(tempFile)

Assigning UUID to image assets

UUIDs can also be used when storing image assets in cloud storage.

javascript
import { v4 as uuidv4 } from 'uuid'

const imageId = uuidv4()
const imagePath = `images/${imageId}.png`

console.log(imagePath)

Generating UUID for User Sessions

Assigning session IDs using UUID

A session ID can be created when a user logs in.

javascript
import { v4 as uuidv4 } from 'uuid'

const sessionId = uuidv4()
console.log("Session ID:", sessionId)

Using UUID for authentication tokens

UUIDs can serve as temporary authentication tokens.

javascript
import { v4 as uuidv4 } from 'uuid'

const authToken = uuidv4()

console.log("Auth Token:", authToken)

These tokens can be stored in cookies or session storage.

Generating unique event identifiers

Applications can generate UUIDs to identify events such as purchases or user actions.

javascript
import { v4 as uuidv4 } from 'uuid'

const eventId = uuidv4()

console.log("Event ID:", eventId)

Using UUID for tracking user actions

Analytics systems can attach UUIDs to user activity logs.

javascript
import { v4 as uuidv4 } from 'uuid'

const actionId = uuidv4()

console.log("User action ID:", actionId)

This allows each event to be uniquely tracked in logs or analytics systems.


Generating Multiple UUIDs

In some applications you may need to generate multiple UUIDs at once. This is common when creating test data, assigning IDs to multiple records, or processing batches of jobs.

Generating UUID inside loops

You can generate UUID values inside loops when creating multiple objects or records.

javascript
import { v4 as uuidv4 } from 'uuid'

for (let i = 0; i < 5; i++) {
  console.log(uuidv4())
}

Example output

3e2d2f6c-5b88-4d32-bd0a-7a9c0f5a2d91
4f3c1e7d-1b23-4d21-9d11-4e7f9d61d0d1
6e2a7c11-1b6d-42f9-b6c0-2e3e0a8a1d2f

Each iteration generates a completely new random UUID.

Creating batch UUID generators

You can create a reusable function that generates multiple UUID values in a batch.

javascript
import { v4 as uuidv4 } from 'uuid'

function generateUUIDBatch(count) {
  const ids = []
  for (let i = 0; i < count; i++) {
    ids.push(uuidv4())
  }
  return ids
}

console.log(generateUUIDBatch(5))

Generating arrays of UUID values

JavaScript provides convenient ways to generate arrays of UUIDs using functional methods.

javascript
import { v4 as uuidv4 } from 'uuid'

const ids = Array.from({ length: 5 }, () => uuidv4())

console.log(ids)

Parallel UUID generation in Node.js

UUID generation is lightweight and can easily run in parallel when processing tasks.

javascript
import { v4 as uuidv4 } from 'uuid'

const tasks = Array.from({ length: 5 }, () => uuidv4())

Promise.all(tasks).then(results => {
  console.log(results)
})

Validating and Parsing UUID in Node.js

Checking if a string is valid UUID

You can validate whether a string follows the UUID format using the validate() function.

javascript
import { validate } from 'uuid'

const id = "550e8400-e29b-41d4-a716-446655440000"

console.log(validate(id))

Example output

true

Parsing UUID to byte arrays

The parse() function converts a UUID string into a byte array.

javascript
import { parse } from 'uuid'

const bytes = parse("550e8400-e29b-41d4-a716-446655440000")

console.log(bytes)

Converting byte arrays back to UUID

You can convert byte arrays back to UUID strings using the stringify() function.

javascript
import { parse, stringify } from 'uuid'

const bytes = parse("550e8400-e29b-41d4-a716-446655440000")
const uuidString = stringify(bytes)

console.log(uuidString)

The output will match the original UUID value.

Detecting UUID version

You can detect which version of UUID is being used.

javascript
import { version } from 'uuid'

const id = "550e8400-e29b-41d4-a716-446655440000"

console.log(version(id))

Example output

4

This helps identify whether the UUID is timestamp-based, namespace-based, or randomly generated.


UUID Versions Explained

UUID version 1 (timestamp based)

Version 1 UUIDs are generated using a timestamp combined with the machine's MAC address.

Characteristics:

  • Time-based identifiers
  • Can be sorted by creation time
  • Slightly predictable due to timestamp information

Example

javascript
import { v1 as uuidv1 } from 'uuid'

console.log(uuidv1())

UUID version 3 (namespace with MD5)

Version 3 UUIDs generate deterministic identifiers using the MD5 hashing algorithm.

If the same namespace and input value are provided, the same UUID will always be produced.

javascript
import { v3 as uuidv3 } from 'uuid'

const id = uuidv3("example.com", uuidv3.DNS)

console.log(id)

UUID version 4 (random UUID)

Version 4 UUIDs are the most commonly used identifiers in modern applications.

They are generated using random values, making collisions extremely unlikely.

javascript
import { v4 as uuidv4 } from 'uuid'

console.log(uuidv4())

UUID version 5 (namespace with SHA-1)

Version 5 UUIDs work similarly to version 3 but use the SHA-1 hashing algorithm.

javascript
import { v5 as uuidv5 } from 'uuid'

const id = uuidv5("example.com", uuidv5.DNS)

console.log(id)

Version 5 is often preferred over version 3 due to stronger hashing.


Node.js UUID vs Other Unique ID Generators

UUID vs NanoID

NanoID is a small and fast ID generator designed for web applications.

Key differences:

FeatureUUIDNanoID
Length36 characters~21 characters
Collision probabilityExtremely lowExtremely low
PerformanceModerateFaster
ReadabilityStandardized formatShorter IDs

Example NanoID usage

javascript
import { nanoid } from 'nanoid'

console.log(nanoid())

UUID vs uniqid module

The uniqid module generates IDs based on timestamps and process information.

Example

javascript
const uniqid = require('uniqid')

console.log(uniqid())

Compared to UUID, uniqid is faster but less standardized.

UUID vs crypto random bytes

The Node.js crypto module can generate random identifiers.

javascript
const { randomBytes } = require('crypto')

const id = randomBytes(16).toString('hex')

console.log(id)

UUID vs Math.random()

Using Math.random() is generally not recommended for generating unique identifiers.

javascript
const id = Math.random().toString(36).substring(2)

console.log(id)

Although simple, this method is not cryptographically secure and may produce collisions in large systems.


Frequently Asked Questions

1. How do you generate UUID in Node.js?

You can generate UUID in Node.js using the uuid npm package with uuid.v4() or using the built-in crypto.randomUUID() method available in modern Node.js versions.

2. What is UUID in Node.js?

UUID stands for Universal Unique Identifier. It is a 128-bit unique value used to identify objects, records, or resources uniquely in distributed systems.

3. What is the difference between UUID and GUID?

UUID and GUID refer to the same concept of globally unique identifiers. GUID is Microsoft's term while UUID is the standardized term defined by RFC 4122.

4. Can Node.js generate UUID without external libraries?

Yes. Modern Node.js versions include crypto.randomUUID() which can generate UUID v4 without installing external packages.

5. Which UUID version should be used in Node.js?

UUID version 4 (v4) is commonly used because it generates random identifiers and is suitable for most applications.

Summary

Generating UUIDs in Node.js is a reliable way to create unique identifiers for databases, APIs, files, sessions, and distributed systems. The most common approach is using the uuid npm package, which supports multiple UUID versions such as v1, v3, v4, and v5.

Modern Node.js versions also provide a built-in method crypto.randomUUID() that allows developers to generate random UUIDs without installing external libraries. For most applications, UUID v4 is the preferred choice because it produces random identifiers with an extremely low probability of collision.

Depending on the use case, developers can also validate, parse, and convert UUID values using utilities provided by the uuid library. Understanding different UUID versions and generation methods helps developers choose the most suitable approach for scalable and distributed Node.js applications.


Official Documentation

For more details about UUID generation and Node.js APIs, refer to the official documentation:

Steve Alila

Steve Alila

Specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly.