How to generate a GUID in Javascript
JavaScript is a powerful and flexible programming language that is used for web development, in web applications, for game development, and lots more. It allows you to implement dynamic features on web pages that cannot be done with only HTML and CSS. It is one of the 3 languages all web developers must learn: HTML to define the content of web pages, CSS to specify the layout of web pages, and JavaScript to program the behavior of web pages.
Modern Native UUID Generation
In modern JavaScript environments (all modern browsers, Node.js 19+, Bun, and Deno), you can generate a cryptographically secure RFC 4122 / RFC 9562 compliant Version 4 UUID natively using the built-in Web Cryptography API:
// Native Web Cryptography API (Browsers, Node.js 19+, Bun, Deno)
const uuid = crypto.randomUUID();
console.log(uuid);
// Output example: "36b8f84d-df4e-4d49-b662-bcde71a8764f"Explanation (Modern Standard)
crypto.randomUUID()is a standard method available on the globalcryptoobject.- It returns a cryptographically secure, random 36-character Version 4 UUID string in standard canonical format (8-4-4-4-12).
- It requires no external dependencies and is supported natively across browsers and modern server-side runtimes.
Legacy / Fallback Implementation
If targeting older environments without native crypto.randomUUID() support, a custom function can be used. Note that standard UUIDs require specific version bits (setting the 13th hex digit to 4) and variant bits (setting the 17th hex digit to 8, 9, a, or b):
// RFC-compliant v4 fallback using crypto.getRandomValues
function generateUUID() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
console.log(generateUUID());Explanation
- This function uses the template string and replaces template placeholders with random hexadecimal values.
- It ensures the version nibble is fixed to
4and the variant bits are set according to RFC specifications. - In modern production code, prefer
crypto.randomUUID()or theuuidpackage.