Menu

How to Generate GUIDs in JavaScript

How to Generate GUIDs in JavaScript

Generating unique ID's is a common practice in most modern web applications. Whether you're building APIs, databases, or client-side applications, there will be situations where you need a Globally Unique Identifier (GUID), also known as UUID (Universally Unique Identifier) in order to uniquely identify some form of data.

Unfortunately, JavaScript doesn't have any built-in method to generate GUIDs like other programming languages do. But that doesn't mean that it isn't possible. In this article I will cover a few of the ways that you can generate GUID's in JavaScript.

What is a GUID?

A GUID (Globally Unique Identifier) is a 128-bit number used to uniquely identify information in computer systems. It is primarily used to ensure that an ID is distinct across different systems and platforms, avoiding the risk of duplicate data.

A GUID generally looks like this:

123e4567-e89b-42d3-a456-426614174000

And the format of a GUID is the following:

xxxxxxxx-xxxx-4xxx-Nxxx-xxxxxxxxxxxx

The format is made up of hexadecimal digits, broken down into five groups separated by hyphens. The 13th character is the version digit, in this case 4, which specify which version of a GUID is being defined.

The probability of generating two identical GUIDs is extremely low, which makes them ideal for many use cases, including databases, session tracking, and unique object identification in code.

Method 1: Using native JavaScript

Although JavaScript doesn’t provide a built-in GUID function, you can generate a reasonably good GUID using a combination of native functions such as Math.random()Date.now(), and toString(16) to create a GUID-like string.

Here’s a simple function to generate a GUID:

function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0, // random integer between 0 and 15
          v = c === 'x' ? r : (r & 0x3 | 0x8); // bitwise operations to handle 'y' and 'x'
    return v.toString(16);
  });
}

console.log(generateGUID());

How it works

This version uses native JavaScript functions in order to generate the 128-bit string.

Math.random() is used to generates a random number in JavaScript. replace() is used to swap out each x or y in the string with a random hexadecimal digit.

4xxx guarantees that the 13th character will be 4, complying with the GUID version standard. yxxx ensures the first bit of the third group is either 8, 9, A, or B.

This method is easy to implement and generates a GUID-like string, but there’s a small risk of collisions when working at a massive scale.

Method 2: Using the Crypto API for better randomness

For a more secure approach, the Crypto API in JavaScript provides better randomness than Math.random(), which can lead to a higher quality of unique identifiers.

This mainly applies if you are working with a vast amount of identifiers however.

Here’s how to use the crypto.getRandomValues() function to generate a GUID:

function generateCryptoGUID() {
  const array = new Uint8Array(16);
  window.crypto.getRandomValues(array);

  array[6] = (array[6] & 0x0f) | 0x40; // UUID version 4
  array[8] = (array[8] & 0x3f) | 0x80; // UUID variant

  return [...array].map((byte, index) => {
    const hex = byte.toString(16).padStart(2, '0');
    if (index === 4 || index === 6 || index === 8 || index === 10) return `-${hex}`;
    return hex;
  }).join('');
}

console.log(generateCryptoGUID());

The real magic here happens within crypto.getRandomValues(). If you were to console log its value ,it would look something like the following:

The rest of the function is straight forward and essentially swaps out the appropriate UUID version and variant values and adds hyphens at the desired breakpoints.

Why use the Crypto API?

The JavaScript Crypto API provides cryptographically strong random values. It reduces the chance of GUID collisions in large-scale applications.

Method 3: Using Popular Libraries to Generate GUIDs

Several popular JavaScript libraries simplify GUID generation. If you’re working in a large project or want to avoid reinventing the wheel, using a dedicated library can save time and ensure correctness.

1. UUID Library

The uuid library is widely used and reliable for generating various types of UUIDs (v1, v4, etc.).

Install it using npm:

npm install uuid

Once installed, you can generate a UUID like this:

const { v4: uuidv4 } = require('uuid');

console.log(uuidv4());

The uuid library provides high-quality randomness and is a great choice if you need to adhere to the UUID standard.

Method 4: Combining time and randomness

If you need a method that balances between speed and uniqueness without relying on external libraries, you can combine the current timestamp and randomness.

Here’s an example:

function generateTimeBasedGUID() {
  const timestamp = Date.now().toString(16);  // Get the current timestamp in hexadecimal format
  const template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; // GUID template

  return template.replace(/[xy]/g, function (c) {
    const random = (parseInt(timestamp.slice(-8), 16) + Math.random() * 16) % 16 | 0;
    const value = c === 'x' ? random : (random & 0x3) | 0x8;  // Adjust bits for GUID compliance
    return value.toString(16);
  });
}

console.log(generateTimeBasedGUID());

This method is useful for generating IDs in quick succession while still maintaining some randomness, though it’s less reliable for use across distributed systems.

Here's a quick breakdown on how it works under the hood:

Timestamp: Date.now() gives the current time in milliseconds. We convert it to hexadecimal using .toString(16) to make it part of the identifier.

Template: We use the standard GUID template: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.

Random Values: For each x and y in the template, we use a combination of the timestamp and random values generated via Math.random().

Version and Variant: The 13th character is fixed to 4 to ensure it's a version 4 UUID, and the first bit of the 17th character is set to 8, 9, A, or B to comply with the variant format.

Choosing the right method

Your choice of GUID generation method depends on the specific requirements of your application:

For simple projects or cases where collisions aren’t a critical concern, the native JavaScript or time-based methods are often good enough.

For secure, large-scale applications, you should rely on the Crypto API or libraries like uuid for added reliability.

Why Generate GUIDs in JavaScript?

There are several use cases where GUIDs are useful in JavaScript:

Assigning unique identifiers to database entries.

Tracking session or transaction IDs.

Assigning unique keys for front-end elements like in React.

Ensuring uniqueness across distributed systems.

While back-end languages like C# or Java have built-in methods for generating GUIDs, JavaScript requires a bit more work.

Conclusion

GUID generation in JavaScript is straightforward once you understand the requirements and limitations of each method. Whether you're generating identifiers for small-scale apps or large, secure systems, JavaScript offers several options to ensure uniqueness.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment