Skip to content

Generate UUID in JavaScript

The simplest way to generate a UUID in JavaScript is to use the built-in function crypto.randomUUID(). Note that this function is only available when your page is served from localhost or via https

javascript
var uuid = crypto.randomUUID();
console.log("Generated UUID: " + uuid);

If you need to generate a specific UUID version, you need to use a third-party library such as uuid which offers more flexible options:

javascript
import { v1, v3, v4, v5, v6, v7 } from 'uuid';

console.log("UUID version 1: " + v1());
console.log("UUID version 3: " + v3(name, v4()));
console.log("UUID version 4: " + v4());
console.log("UUID version 5: " + v5(name, v4()));
console.log("UUID version 6: " + v6());
console.log("UUID version 7: " + v7());

The Online UUID Generator on this site was implemented using this library, so another way to see it in action is to open it and view the page source.

Installation & Setup

Browser (CDN):

html
<script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script>

Node.js (npm):

bash
npm install uuid

UUID Version Comparison

Choose the right version for your needs:

  • Version 1 - Time-based, includes MAC address
  • Version 3 - MD5 namespace-based, deterministic
  • Version 4 - Random, most popular choice
  • Version 5 - SHA-1 namespace-based, more secure than v3
  • Version 6 - Time-ordered, better than v1 for databases
  • Version 7 - Modern time-based with improved sorting

For JavaScript applications:

  • Web APIs: Use Version 4 for session IDs and tokens
  • Database records: Consider Version 7 for better indexing
  • Deterministic needs: Use Version 5 for consistent IDs

How do I generate UUID in other languages?

Similar JVM languages:

  • TypeScript - Same methods with type safety
  • Java - Enterprise applications
  • Kotlin - Android and server development

Other popular languages:

  • Python - Built-in uuid module
  • Bash - uuidgen command-line tool

← Back to Online UUID Generator