How to Generate a UUID in JavaScript

    Create a UUID in the browser with the native crypto.randomUUID() API, with a fallback for older environments.

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

    Modern browsers expose a built-in crypto.randomUUID() method that returns a cryptographically strong random version 4 UUID as a string. It needs no libraries and is the simplest way to generate a UUID in JavaScript.

    Below are the native approach, a fallback for older browsers, and the npm package option for shared front-end/back-end code.

    The native way: crypto.randomUUID()

    crypto.randomUUID() is available in all current browsers (over secure contexts, i.e. https or localhost) and returns a ready-to-use UUID string.

    javascript
    const id = crypto.randomUUID();
    console.log(id); // "36b8f84d-df4e-4d49-b662-bcde71a8764f"

    A fallback for older environments

    If you must support environments without crypto.randomUUID(), build a v4 UUID from crypto.getRandomValues() so it is still based on a strong random source.

    javascript
    function uuidv4() {
      if (crypto.randomUUID) return crypto.randomUUID();
      return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) =>
        (
          +c ^
          (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))
        ).toString(16)
      );
    }
    
    console.log(uuidv4());

    Using the uuid npm package

    For bundled apps the uuid package gives you every version (v1, v4, v5, v7) with a consistent API and works in both Node and the browser.

    javascript
    import { v4 as uuidv4 } from "uuid";
    
    console.log(uuidv4()); // "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

    Frequently asked questions

    Is crypto.randomUUID() supported in all browsers?
    It is supported in all current major browsers, but only in secure contexts (https or localhost). Use a fallback if you must support very old browsers.
    Do I need a library to generate a UUID in JavaScript?
    No. crypto.randomUUID() is built in. A library like uuid is only needed if you want versions other than v4 or broader environment support.
    Is crypto.randomUUID() random enough?
    Yes. It uses a cryptographically strong random number generator, making it suitable for IDs that should be hard to guess.

    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.