Skip to main content

How to Generate UUID in Node.js

Native crypto API & uuid package

Use the code examples below to generate UUIDs in Node.js with the native crypto.randomUUID() method (available since Node 14.17+) or the uuid npm package for v1, v4, v5, and v7 support. Copy these Node.js UUID snippets into your Express routes, database models, or server-side scripts for unique identifier generation in APIs, microservices, file uploads, session management, and any backend JavaScript application. The javascript uuid guide covers crypto.randomUUID() for browsers and the uuid npm package for Node.js projects.

Generate UUID in Node.js

crypto.randomUUID()
550e8400-e29b-41d4-a716-446655440000

Node.js UUID Evolution Timeline

Node.js < 14.17 Legacy

Third-Party Only

Required uuid npm package for UUID generation

npm install uuid
Node.js 14.17 - 15.x Transition

crypto.randomUUID() Introduced

Native UUID v4 generation added to crypto module

const { randomUUID } = require('crypto');
Node.js 16+ (Current) ✓ Recommended

Native UUID Standard

Stable crypto.randomUUID() with ES Modules support

import { randomUUID } from 'crypto';

Generate UUID with Native Node.js Crypto Module

✓ No Dependencies Required

Built into Node.js 14.17.0 and later. Zero npm packages needed! The python uuid reference shows how to use uuid.uuid4() as a Django model default without extra dependencies.

CommonJS

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

const uuid = randomUUID();
console.log(uuid);

ES Modules

import { randomUUID } from 'crypto';

const uuid = randomUUID();
console.log(uuid);

Async/Await UUID Generation Patterns

async-uuid.js
import { randomUUID } from 'crypto';

// Async function with UUID generation
async function createUser(name, email) {
    const userId = randomUUID();
    
    // Simulate database operation
    const user = {
        id: userId,
        name,
        email,
        createdAt: new Date().toISOString()
    };
    
    await saveToDatabase(user);
    return user;
}

// Generate multiple UUIDs asynchronously
async function generateBatchUUIDs(count) {
    const uuids = [];
    
    for (let i = 0; i < count; i++) {
        // Synchronous UUID generation in async context
        uuids.push(randomUUID());
    }
    
    return uuids;
}

// Usage
(async () => {
    const user = await createUser('Alice', '[email protected]');
    console.log('Created user:', user.id);
    
    const batchUuids = await generateBatchUUIDs(100);
    console.log(`Generated ${batchUuids.length} UUIDs`);
})();

Express.js Middleware: Request UUID Tracking

Automatic Request ID Generation

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

const app = express();

// Middleware: Add UUID to every request
app.use((req, res, next) => {
    req.id = randomUUID();
    res.setHeader('X-Request-ID', req.id);
    console.log(`[${req.id}] ${req.method} ${req.path}`);
    next();
});

// Route handler with request tracking
app.post('/users', async (req, res) => {
    const userId = randomUUID();
    
    console.log(`[${req.id}] Creating user with ID: ${userId}`);
    
    const user = {
        id: userId,
        ...req.body,
        createdAt: new Date()
    };
    
    res.json({ requestId: req.id, user });
});

app.listen(3000);

Advanced Logging with UUID Correlation

import winston from 'winston';
import { randomUUID } from 'crypto';

// Logger with correlation ID
const logger = winston.createLogger({
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
    ),
    transports: [new winston.transports.Console()]
});

// Middleware with structured logging
app.use((req, res, next) => {
    req.id = randomUUID();
    
    req.log = (level, message, meta = {}) => {
        logger.log({
            level,
            message,
            requestId: req.id,
            method: req.method,
            path: req.path,
            ...meta
        });
    };
    
    req.log('info', 'Request started');
    next();
});

UUID npm Package: All Versions Support

For UUID v1, v5, v6, and v7 support, install the uuid package: For cross-platform UUID generation in Flutter, the dart uuid guide covers iOS, Android, and web targets.

npm Package Installation

npm install uuid
uuid-all-versions.js
import { v1, v4, v5, v7, validate, version } from 'uuid';

// UUID v4 - Random (most common)
const uuidV4 = v4();
console.log('v4:', uuidV4);

// UUID v1 - Timestamp + MAC address
const uuidV1 = v1();
console.log('v1:', uuidV1);

// UUID v7 - Unix timestamp (sortable, database-optimized)
const uuidV7 = v7();
console.log('v7:', uuidV7);

// UUID v5 - SHA-1 hash (deterministic)
const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const uuidV5 = v5('example.com', NAMESPACE);
console.log('v5:', uuidV5);

// Validate UUID
console.log('Valid:', validate(uuidV4));  // true

// Get version
console.log('Version:', version(uuidV4));  // 4

MongoDB Integration with UUID Primary Keys

mongodb-uuid.js
import { MongoClient } from 'mongodb';
import { randomUUID } from 'crypto';

const client = new MongoClient('mongodb://localhost:27017');

async function createUser(name, email) {
    await client.connect();
    const db = client.db('myapp');
    const users = db.collection('users');
    
    const user = {
        _id: randomUUID(),  // Use UUID instead of ObjectId
        name,
        email,
        createdAt: new Date()
    };
    
    await users.insertOne(user);
    console.log('Created user:', user._id);
    return user;
}

async function getUserById(uuid) {
    await client.connect();
    const db = client.db('myapp');
    
    return await db.collection('users').findOne({ _id: uuid });
}

Session Management with UUID Tokens

session-manager.js
import { randomUUID } from 'crypto';

class SessionManager {
    constructor() {
        this.sessions = new Map();
    }
    
    createSession(userId) {
        const sessionId = randomUUID();
        const expiresAt = Date.now() + (24 * 60 * 60 * 1000); // 24 hours
        
        this.sessions.set(sessionId, {
            userId,
            createdAt: Date.now(),
            expiresAt
        });
        
        return sessionId;
    }
    
    validateSession(sessionId) {
        const session = this.sessions.get(sessionId);
        
        if (!session) return null;
        if (Date.now() > session.expiresAt) {
            this.sessions.delete(sessionId);
            return null;
        }
        
        return session;
    }
    
    destroySession(sessionId) {
        return this.sessions.delete(sessionId);
    }
}

// Usage in Express
const sessionManager = new SessionManager();

app.post('/login', (req, res) => {
    const sessionId = sessionManager.createSession(req.body.userId);
    res.cookie('session', sessionId, { httpOnly: true });
    res.json({ sessionId });
});

Comments & Feedback

Share your experience or ask questions about this tool

Copied!