How to Generate UUIDs in JavaScript, Python, and SQL — A Cookbook

Every language and database has a built-in way to generate UUIDs, and in 2026 you almost never need a third-party library for the basics. This cookbook collects the recipes you will actually use: crypto.randomUUID() in the browser and Node.js, Python's uuid module including deterministic namespace UUIDs, MySQL's UUID() with UUID_TO_BIN(), and PostgreSQL's gen_random_uuid() — plus how to store the results efficiently so your indexes do not bloat.

JavaScript: Browser and Node.js

The one-liner that covers 95% of cases — built into every modern browser and Node.js 19+ (available under a flag from 14.17):

// Browser (secure context: HTTPS or localhost) and Node.js
const id = crypto.randomUUID();
// '36b8f84d-df4e-4d49-b662-bcde71a8764f'  (version 4)

// Node.js — explicit import if you prefer
import { randomUUID } from 'node:crypto';
const orderId = randomUUID();

crypto.randomUUID() uses a cryptographically secure random source and returns a lowercase v4 string. Two things to know: in browsers it only exists in secure contexts (HTTPS or localhost), and it generates v4 only. For time-ordered v7 or name-based v5, use the well-known uuid npm package:

npm install uuid

import { v4, v5, v7 } from 'uuid';

v4();                                  // random
v7();                                  // time-ordered, index-friendly
v5('dev-brains-ai.com', v5.DNS);       // deterministic (same in, same out)

Python: The uuid Module

Python has shipped a full uuid module in the standard library since 2.5 — no pip install required:

import uuid

# Random v4 — the everyday choice
uuid.uuid4()
# UUID('4b166dbe-d99d-4e63-8d99-5c53d7c286f7')

str(uuid.uuid4())    # '1cfd7d8f-...' as a plain string
uuid.uuid4().hex     # 32 hex chars, no dashes
uuid.uuid4().bytes   # raw 16 bytes for binary storage

The underrated feature is uuid5 — deterministic, name-based UUIDs. You hash a namespace UUID plus any string, and the same inputs always produce the same UUID, on any machine, in any language:

# Built-in namespaces: NAMESPACE_DNS, NAMESPACE_URL,
# NAMESPACE_OID, NAMESPACE_X500
uuid.uuid5(uuid.NAMESPACE_DNS, 'dev-brains-ai.com')
# UUID('6ed258d2-...') — identical every run

# Your own namespace: generate ONE v4, hard-code it forever
APP_NS = uuid.UUID('8c0fb5a6-6c14-4b47-8f4e-2d0a3c9b7e11')

def customer_uuid(email: str) -> uuid.UUID:
    return uuid.uuid5(APP_NS, email.lower())

# Re-running an import never creates duplicate IDs

This pattern makes data imports idempotent: the row for a given email address always maps to the same UUID, so re-importing updates instead of duplicating. Python 3.14 adds native uuid.uuid7(); on older versions use the uuid6 package from PyPI.

MySQL: UUID() and UUID_TO_BIN()

MySQL's UUID() function returns a version 1 (time-based) UUID as text. The important part is storing it as BINARY(16), not CHAR(36), using the conversion helpers added in MySQL 8:

SELECT UUID();
-- '6ccd780c-baba-1026-9564-5b8c656024db'  (version 1)

CREATE TABLE orders (
  id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1)),
  customer VARCHAR(100)
);

-- Insert and read back
INSERT INTO orders (customer) VALUES ('Asha');
SELECT BIN_TO_UUID(id, 1) AS id, customer FROM orders;

The second argument 1 to UUID_TO_BIN(uuid, swap_flag) is a clever trick: it swaps the time-low and time-high fields of the v1 UUID so the most significant bytes become the timestamp. Stored that way, keys arrive in roughly ascending order and behave like sequential IDs in the clustered index — MySQL's own workaround for the random-insert problem. Always use the same flag in BIN_TO_UUID() when reading.

PostgreSQL: gen_random_uuid() and the uuid Type

PostgreSQL is the most pleasant of the three: it has a first-class uuid column type (16 bytes internally, rendered as the familiar 36-character text), and since version 13 gen_random_uuid() is built in — no extension needed:

SELECT gen_random_uuid();
-- 5b30857e-... (version 4)

CREATE TABLE orders (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  customer text
);

-- PostgreSQL 18+: time-ordered v7, better for busy tables
CREATE TABLE events (
  id uuid PRIMARY KEY DEFAULT uuidv7(),
  payload jsonb
);

On versions before 13, enable pgcrypto with CREATE EXTENSION pgcrypto; to get gen_random_uuid(). The older uuid-ossp extension also offers uuid_generate_v4() and uuid_generate_v5() if you need name-based UUIDs in SQL.

Storing UUIDs Efficiently: The Rules

  • PostgreSQL — always the native uuid type. 16 bytes, validated, indexed efficiently.
  • MySQL / MariaDBBINARY(16) with UUID_TO_BIN(..., 1) / BIN_TO_UUID(..., 1). MariaDB 10.7+ also has a native UUID type.
  • SQL Server — the uniqueidentifier type with NEWID(), or NEWSEQUENTIALID() for ordered keys.
  • Never CHAR(36)/VARCHAR(36) — text storage is 36+ bytes vs 16, comparisons are slower, and every secondary index inherits the bloat.
  • Prefer time-ordered generation (UUIDv7, or MySQL's swap flag) for primary keys on insert-heavy tables.
  • Generate where it is convenient — app-side generation lets you know the ID before the INSERT; database defaults guarantee no row ever lacks one. Both are fine; pick one per table and stay consistent.

Need a few UUIDs right now for a test fixture, a seed script, or an API call? The free UUID generator creates single or bulk UUIDs in your browser with one click.

Frequently Asked Questions

How do I generate a UUID in JavaScript without a library?

Call crypto.randomUUID(). It is built into all modern browsers and Node.js 19+, uses a cryptographically secure random source, and returns a standard version 4 UUID string. No npm package is needed for basic v4 generation. Note that in browsers it requires a secure context (HTTPS or localhost).

What is the difference between uuid4 and uuid5 in Python?

uuid.uuid4() generates a random UUID — different every call. uuid.uuid5(namespace, name) hashes a namespace UUID and a name string with SHA-1 to produce a deterministic UUID — the same inputs always give the same output. Use uuid4 for new unique IDs and uuid5 for reproducible IDs derived from existing keys.

How should I store UUIDs in MySQL and PostgreSQL?

In PostgreSQL, use the native uuid column type, which stores the value in 16 bytes. In MySQL, use BINARY(16) and convert with UUID_TO_BIN() and BIN_TO_UUID(). Avoid CHAR(36) text columns — they use more than double the storage and make every index larger and slower.

Try the Free UUID Generator

Generate UUIDs instantly in your browser — single or in bulk — and copy them with one click. No signup, no cost.

Related articles