Skip to main content
JS

How to Generate UUID in JavaScript

Modern browser API & npm packages

Every JavaScript app eventually needs a unique identifier, and the built-in crypto.randomUUID() method makes it a one-liner — no library required. Call it in any modern browser or Node.js environment to get back a random, RFC 4122-compliant UUID as a plain string, ready to use as a database key, session token, or list identifier. Below you'll find copy-paste ready code for generating a UUID in JavaScript, checking whether a string is a well-formed UUID, and the uuid npm package for the versions and environments the native API doesn't cover. See the node.js uuid page for Express and Fastify UUID patterns, including request ID middleware.

Generate UUID in JavaScript

crypto.randomUUID()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in JavaScript

The simplest way to generate a UUID in JavaScript is crypto.randomUUID(), built into every modern browser (Chrome 92+, Firefox 95+, Safari 15.4+) and Node.js (available globally on Node 19+, or via require('crypto') on Node 14.17+/16.7+) with zero dependencies. The c++ uuid reference explains how to generate and parse UUIDs in C++ with proper formatting.

app.js (browser or Node.js 19+)
const myUuid = crypto.randomUUID();
console.log(myUuid);
// Output: 550e8400-e29b-41d4-a716-446655440000
server.js (older Node.js)
const { randomUUID } = require('crypto');

const myUuid = randomUUID();
console.log(myUuid);
// Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in JavaScript

JavaScript has no dedicated UUID type — a UUID is just a string — so "converting" one really means validating that a string is well-formed before you trust it. See the python uuid generator page for UUID validation regex, error handling, and framework-specific integration examples.

app.js
function isValidUUID(str) {
  const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
  return regex.test(str);
}

console.log(isValidUUID('550e8400-e29b-41d4-a716-446655440000')); // true
console.log(isValidUUID('not-a-uuid')); // false
app.js (uuid package)
import { validate, version } from 'uuid';

const str = '550e8400-e29b-41d4-a716-446655440000';
console.log(validate(str)); // true
console.log(version(str)); // 4

Explanation

Other Options for Generating UUIDs in JavaScript

crypto.randomUUID() only produces version 4 UUIDs, so reach for the uuid npm package when you need version 1, 5, or 7 identifiers, or support for older browsers and Node.js versions where the native API isn't available.

Terminal
npm install uuid
app.js
import { v4 as uuidv4, v7 as uuidv7 } from 'uuid';

// Version 4 - random, same style as crypto.randomUUID()
const randomId = uuidv4();

// Version 7 - Unix timestamp + random, sortable and index-friendly
const sortableId = uuidv7();

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!