Generate a UUID in JavaScript

JavaScript is the most popular programming language in the world!

Since it's creation in 1995 for use in the Netscape browser, JavaScript's popularity has exploded to become the predominant language of the Web. Today, JavaScript powers everything from interactive web pages to dynamic web and mobile apps to backend web services.

How to Generate a UUID in JavaScript

Although the JavaScript language itself does not have built-in support for generating a UUID or GUID, there are plenty of quality 3rd party, open-source libraries that you can use.

The JavaScript library we recommend for generating UUIDs is called (unsurprisingly), uuid. It can generate version 1, 3, 4 and 5 UUIDs.

Installing the uuid Package

To get started with the library, you'll need to install it. If you're working in a project with a package.json file, run this command to add it to the dependencies list:

% npm install uuid

Or if you want to install it globally on your computer, use this command:

% npm install -g uuid

Generating UUIDs

With the uuid library installed, you can now use it in your JavaScript code.

Here's how you can generate a version 4 UUID in JavaScript with the uuid library:

import {v4 as uuidv4} from 'uuid';
let myuuid = uuidv4();
console.out('Your UUID is: ' + myuuid);

Explanation

  • Line #1 imports the version 4 UUID function. There are also functions available for generating version 1, 3 and 5 UUIDs. Note that this is the ES6 module import syntax.
  • Line #3 generates the UUID and saves it in the variable, myuuid.
  • The output from line #5 will be something like:
    Your UUID is: c32d8b45-92fe-44f6-8b61-42c2107dfe87
    

The uuid library has a number of other functions, such as for converting from a string representation of a UUID into a byte array and back. You can read more about the JavaScript uuid library on it's GitHub page.


How can we improve this page? Let us know!




The UUIDs generated by this site are provided AS IS without warranty of any kind, not even the warranty that the generated UUIDs are actually unique. You are responsible for using the UUIDs and assume any risk inherent to using them. You are not permitted to use the UUIDs generated by this site if you do not agree to these terms. Do not use any UUIDs found on cached versions of this page.
Privacy Policy
This website uses cookies. We use cookies to personalise content/ads and to analyse our traffic.

The UUIDs generated by this site conform to RFC 4122 whenever possible.
Read more about UUIDs at Wikipedia.
Check out our developer API.

Copyright © 2021 TransparenTech LLC. All Rights Reserved. Contact Us.