Skip to main content

Searching...

Tools
Articles
View All Results

Developer Lab · Node.js

Generate UUID in Node.js

Node.js has built-in UUID v4 generation via crypto.randomUUID() since v14.17.0 - zero dependencies, OS CSPRNG-backed. Use the uuid package for v7 and v5 support.

Quick Reference

Function Version Sortable Use Case
crypto.randomUUID() v4 No General purpose - zero deps, built-in since Node 14.17
uuidv7() from uuid v7 Yes Database PKs, event logs - time-ordered
uuidv5() from uuid v5 No Deterministic - same namespace + name = same UUID

Primary Implementation

Production Ready
javascript
// ESM (Node.js 14.17+ - recommended)
import { randomUUID } from 'crypto';

// CommonJS
// const { randomUUID } = require('crypto');

// Generate a UUID v4 - zero dependencies
const id = randomUUID();
console.log(id);
// → "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// Generate multiple
const ids = Array.from({ length: 5 }, () => randomUUID());

// Parse / validate (no built-in - use a regex or the uuid package)
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isValidUUID(str) {
  return UUID_REGEX.test(str);
}

console.log(isValidUUID(id)); // → true

All UUID Versions

UUID v4 - Random (built-in, no deps)

javascript
import { randomUUID } from 'crypto';

// 122 bits of randomness - backed by libuv → OS CSPRNG
const id = randomUUID();
// → "550e8400-e29b-41d4-a716-446655440000"

UUID v7 - Time-ordered (requires uuid package)

javascript
// npm install uuid
import { v7 as uuidv7 } from 'uuid';

// Millisecond-precision timestamp prefix - sorts chronologically
const id = uuidv7();
// → "018e8f6a-1b2c-7d3e-9f4a-5b6c7d8e9f0a"

UUID v5 - Deterministic / Namespace-based

javascript
import { v5 as uuidv5 } from 'uuid';

// SHA-1 hash of namespace + name - same inputs always produce the same UUID
const id = uuidv5('example.com', uuidv5.DNS);
// → always "cfbff0d1-9375-5685-968c-48ce8b15ae17"

Real-World Use Cases

1. Express middleware - request tracing ID

javascript
import express from 'express';
import { randomUUID } from 'crypto';

const app = express();

// Inject a unique request ID into every request
app.use((req, res, next) => {
  req.id = randomUUID();
  res.setHeader('X-Request-ID', req.id);
  next();
});

app.get('/orders', (req, res) => {
  console.log(`[${req.id}] GET /orders`);
  res.json({ requestId: req.id });
});

2. Prisma - UUID primary key

javascript
// schema.prisma
// model User {
//   id    String @id @default(uuid())
//   name  String
// }

import { PrismaClient } from '@prisma/client';
import { randomUUID } from 'crypto';

const prisma = new PrismaClient();

// Prisma generates the UUID automatically via @default(uuid())
// Or supply your own for idempotent inserts:
async function createUser(name) {
  return prisma.user.create({
    data: { id: randomUUID(), name },
  });
}

3. Idempotency key for payment APIs

javascript
import { randomUUID } from 'crypto';

// Generate once, store, reuse on retry - prevents duplicate charges
async function chargeCustomer(customerId, amount) {
  const idempotencyKey = randomUUID();

  const response = await fetch('https://api.stripe.com/v1/charges', {
    method: 'POST',
    headers: {
      'Idempotency-Key': idempotencyKey,
      'Authorization': `Bearer ${process.env.STRIPE_KEY}`,
    },
    body: new URLSearchParams({ customer: customerId, amount }),
  });
  return response.json();
}

Common Mistakes

Using Math.random() for IDs

Math.random() is not cryptographically secure and only provides ~53 bits of entropy. Always use crypto.randomUUID() which is backed by the OS CSPRNG via libuv.

Installing the uuid package just for v4

If you only need UUID v4, crypto.randomUUID() is built-in since Node 14.17. Only add the uuid package when you need v7, v5, or v3.

Mixing ESM and CJS imports

Use import { randomUUID } from 'crypto' in ESM projects and const { randomUUID } = require('crypto') in CJS. Mixing them causes runtime errors. Check your package.json "type" field.

How It Works

crypto.randomUUID() is implemented in V8/libuv and calls the OS CSPRNG directly - /dev/urandom on Linux/macOS and BCryptGenRandom on Windows. It fills 122 bits with random data and sets the version (4) and variant bits per RFC 4122.

The function always returns a lowercase hyphenated string. It is synchronous and does not block the event loop - the OS entropy call is non-blocking.

Output Formats

randomUUID()

f47ac10b-58cc-4372-a567-0e02b2c3d479

No hyphens

randomUUID().replace(/-/g, '')

Uppercase

randomUUID().toUpperCase()

Best Practices, Performance, and Security

Best practices

Use crypto.randomUUID() for v4 - it's built-in, fast, and zero dependencies.

Use UUID v7 for database primary keys - sequential inserts avoid index fragmentation.

Store UUIDs as lowercase strings for consistency across systems.

Performance

Native crypto.randomUUID() runs at roughly 5–10 million UUIDs/second in Node.js. It is implemented in C++ and calls the OS CSPRNG via libuv.

The call is synchronous but non-blocking - it does not yield to the event loop, making it safe to call in hot paths.

Security

Entropy source: libuv → OS CSPRNG (/dev/urandom on Linux/macOS, BCryptGenRandom on Windows). Cryptographically secure.

Suitable for session tokens, CSRF tokens, and API keys. Never use Math.random() for security-sensitive IDs.

Installation

UUID v4 (native)

bash
# No installation needed for v4 (Node 14.17+)

Requires Node.js 14.17.0 or later for the built-in crypto.randomUUID().

uuid package (v7, v5, v3)

bash
npm install uuid   # for v7, v5, v3

The uuid npm package works on all Node versions when you need v7, v5, or v3 support.

Frequently Asked Questions

How do I generate a UUID in Node.js?

Node.js 19+ exposes a global crypto.randomUUID() that returns an RFC 4122 v4 UUID with zero dependencies. On Node 14.17 to 18, import it first with const { randomUUID } = require('node:crypto'). For v7, v5, or v3, install the uuid package.

Is crypto.randomUUID() cryptographically secure?

Yes. crypto.randomUUID() uses the platform CSPRNG (operating system secure random source), suitable for session tokens, API keys, and idempotency keys. Do not use non-cryptographic random sources for security-sensitive identifiers.

What is the difference between UUID v4 and v7 in Node.js?

UUID v4 (crypto.randomUUID() or equivalent) is fully random and not sortable. UUID v7 embeds a millisecond timestamp for chronological sorting (RFC 9562). Use v4 for general-purpose IDs; use v7 for database primary keys at scale.

Do I need to install a package for UUID generation in Node.js?

No additional package is required for basic v4 generation in Node.js. Check the Installation section for version-specific notes.

How do I validate a UUID string in Node.js?

Use the platform's UUID parse/validation function, or test against the RFC 4122 regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. Always validate external input at API boundaries.

Should I use UUIDs as database primary keys in Node.js applications?

UUIDs work well as primary keys for distributed systems. Prefer native UUID/BINARY(16) column types over VARCHAR(36). For very large tables, consider UUID v7 for better B-tree insert locality.

Can I generate UUIDs in Node.js without a network connection?

Yes. UUID generation uses local OS entropy sources and does not require network access. Each call is independent and thread-safe on modern platforms.

What output formats are available in Node.js?

The standard hyphenated lowercase string (36 chars) is the default. Most APIs also support 32-char hex (no hyphens) and 16-byte binary formats. Use string format for APIs and binary for database storage.

What RFC standards apply to Node.js UUID generation?

Version 4 UUIDs follow RFC 4122. UUID v7 follows RFC 9562 (May 2024). Ensure your chosen method produces compliant version and variant bits.

When should I avoid UUID v1?

Avoid UUID v1 in security-sensitive contexts - it embeds MAC address and timestamp information. Prefer v4 (crypto.randomUUID() or equivalent) unless you need legacy Cassandra timeuuid compatibility.

Key definitions

UUID
128-bit universally unique identifier, usually shown as 36 hex characters with hyphens.
CSPRNG
Cryptographically secure pseudo-random number generator - the entropy source behind secure UUID generation.
RFC 4122
IETF standard defining UUID versions 1 through 5. Version 4 is random.
RFC 9562
IETF standard adding UUID versions 6, 7, and 8. Version 7 is time-ordered.