How to Generate a UUID in Node.js

    Use Node's built-in crypto.randomUUID() or the uuid package to create UUIDs server-side.

    Need a UUID right now? Generate one instantly in your browser.

    Node.js can generate UUIDs without any dependencies using crypto.randomUUID(), available since Node 16.7. For more control over the version, the popular uuid package is the standard choice.

    Both approaches are shown below, along with guidance on when to reach for each.

    Built-in: crypto.randomUUID()

    The crypto module exposes randomUUID(), which returns a random v4 UUID string. This is the fastest way to get an ID with zero dependencies.

    javascript
    const { randomUUID } = require("node:crypto");
    
    console.log(randomUUID()); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
    
    // ESM equivalent:
    // import { randomUUID } from "node:crypto";

    The uuid package (v1, v4, v5, v7)

    Install the uuid package when you need versions other than v4. It provides named exports for each version and works the same in CommonJS and ESM.

    bash
    npm install uuid
    javascript
    import { v4 as uuidv4, v7 as uuidv7 } from "uuid";
    
    console.log(uuidv4()); // random
    console.log(uuidv7()); // time-ordered, sortable

    Frequently asked questions

    Do I need the uuid package in Node.js?
    Not for random v4 UUIDs — crypto.randomUUID() is built in. Install uuid only if you need v1, v5, or v7.
    How do I generate a sortable UUID v7 in Node.js?
    Install the uuid package and import { v7 as uuidv7 }, then call uuidv7() for a time-ordered identifier.
    Which Node.js version added crypto.randomUUID()?
    It was added in Node.js 16.7.0 and is available in all later versions.

    Cookie Consent

    We use cookies to enhance your experience on our website. By accepting, you agree to the use of cookies in accordance with our Privacy Policy.