DEV Community

kingfujing
kingfujing

Posted on Originally published at devtoolshub.cloud

How to Generate UUID in JavaScript, Python and SQL

Originally published on DevToolsHub — free, privacy-first online tools for developers.

A UUID (Universally Unique Identifier) is a 128-bit value that identifies
something — a request, a user, a database row — with a collision risk so
small you can generate billions of them without coordination. That
property makes UUIDs the default choice for distributed systems, offline
clients, and anywhere two processes might create records at the same time
without asking a central server for the next ID. Every major platform
ships a one-liner for it: crypto.randomUUID() in JavaScript,
uuid.uuid4() in Python, gen_random_uuid() in
PostgreSQL.

      This guide shows the exact call in each language, how to hand-roll a v4
      UUID in older browsers that lack `randomUUID`, what the version
      digit in a UUID actually means, and how to choose between UUID v4 and the
      newer v7 when the identifier is a database primary key — the one decision
      where the "any version is fine" assumption breaks down.
Enter fullscreen mode Exit fullscreen mode

💡 Quick Try Need a batch of identifiers right now? Our free

UUID Generator

creates v4 UUIDs instantly in your browser, with one-click copy for
single values or bulk lists — no code required.

What Is a UUID? 128 Bits and the Version Digit

      A UUID is 128 bits displayed as 32 hexadecimal digits in five groups:
      `8-4-4-4-12` (for example,
      `3b241101-e2bb-4255-8caf-4136c566a962`). The canonical string
      form is 36 characters including hyphens. Two positions carry meaning
      rather than randomness:
Enter fullscreen mode Exit fullscreen mode
3b241101-e2bb-4255-8caf-4136c566a962
                   ^    ^---- variant bits (fixed for standard UUIDs)
                   |--------- version digit

Version 4: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  (4 = random; y is one of 8, 9, a, b)
Enter fullscreen mode Exit fullscreen mode
      The version digit tells you *how* the UUID was made: **v4**
      is purely random (122 random bits), **v7** embeds a
      millisecond timestamp plus random bits, and older versions v1/v3/v5 derive
      from MAC addresses or namespace hashes. When you generate a UUID today you
      almost always want v4 for random identifiers or v7 for time-ordered ones.
      122 random bits means the chance of two v4 UUIDs colliding is negligible —
      you would need to generate roughly 2.7 quintillion UUIDs for a 50% chance
      of a single duplicate.
Enter fullscreen mode Exit fullscreen mode

Generate a UUID in JavaScript: crypto.randomUUID()

      The modern, built-in way needs no dependencies. It is available in all
      major browsers since 2021-2022 and in Node.js since **14.17**
      (stable since 16.7), exposed globally in both environments:
Enter fullscreen mode Exit fullscreen mode
const id = crypto.randomUUID();
console.log(id);   // e.g. "36b8f84d-df4e-4d49-b662-bcde71a87655"

// Node.js: global crypto since 19+, or import it explicitly on older versions
// import  from "node:crypto";

// Browser support guard
if (crypto.randomUUID) {
  console.log("modern path available");
}
Enter fullscreen mode Exit fullscreen mode
      One constraint trips people up: in browsers,
      **`crypto.randomUUID()` only exists in secure
      contexts** — HTTPS pages and `localhost`. Serve your
      page over plain HTTP on a LAN IP and the method vanishes, throwing
      `crypto.randomUUID is not a function`. The fallback below
      covers exactly that case. Node.js has the same function regardless of any
      "secure context" — the restriction is a browser platform rule.
Enter fullscreen mode Exit fullscreen mode

Fallback: Hand-Rolling a v4 UUID with getRandomValues

      For older environments (legacy browsers, non-secure HTTP contexts), build
      the v4 format yourself from 16 random bytes. The
      `crypto.getRandomValues()` API has existed in browsers since
      2013 and needs no secure context:
Enter fullscreen mode Exit fullscreen mode
function uuidv4() {
  if (crypto.randomUUID) return crypto.randomUUID();   // fast path

  // Fallback: 16 cryptographically random bytes
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  bytes[6] = (bytes[6] & 0x0f) | 0x40;   // set version to 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80;   // set variant to RFC 4122

  const hex = [...bytes].map(b => b.toString(16).padStart(2, "0")).join("");
  return [
    hex.slice(0, 8),
    hex.slice(8, 12),
    hex.slice(12, 16),
    hex.slice(16, 20),
    hex.slice(20, 32),
  ].join("-");
}

console.log(uuidv4());   // valid v4 UUID in any modern browser
Enter fullscreen mode Exit fullscreen mode
      The bit-masking lines matter: `(b & 0x0f) | 0x40` zeroes
      the high nibble of byte 6 and writes `0100` (version 4), while
      `(b & 0x3f) | 0x80` sets the two variant bits that mark the
      UUID as RFC 4122-compatible. Skip them and validators will reject your
      output. If you must support ancient browsers without
      `getRandomValues` too, the classic
      `'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, ...)`
      pattern with `Math.random()` works but is
      **not** cryptographically random — fine for test fixtures,
      not for identifiers that matter.
Enter fullscreen mode Exit fullscreen mode

Generate a UUID in Python: uuid.uuid4()

      Python's standard library has had this since forever. The
      `uuid` module exposes one function per version, plus helpers
      for converting to common string formats:
Enter fullscreen mode Exit fullscreen mode
import uuid

u = uuid.uuid4()
print(u)                  # 3b241101-e2bb-4255-8caf-4136c566a962
print(str(u))             # same, explicit
print(u.hex)              # 3b241101e2bb42558caf4136c566a962 (32 chars, no dashes)
print(u.int)              # as a 128-bit integer

# Python 3.9+ also has time-ordered UUIDs:
print(uuid.uuid7().hex[:12])   # starts with millisecond timestamp

# For a quick batch from the shell:
# python3 -c "import uuid; print('\\n'.join(str(uuid.uuid4()) for _ in range(5)))"
Enter fullscreen mode Exit fullscreen mode
      Under the hood `uuid4()` reads 16 bytes from
      `os.urandom()` — the same cryptographic source the OS uses for
      keys — so it is safe for anything from session tokens to file names. If
      you specifically need time-ordered identifiers server-side, Python 3.9
      added `uuid.uuid7()`, mirroring the v7 draft discussed below.
Enter fullscreen mode Exit fullscreen mode

Generate UUIDs in SQL: PostgreSQL and MySQL

      Letting the database mint the identifier keeps application code simple and
      guarantees uniqueness across every writer touching the table. PostgreSQL
      has a native function behind the `pgcrypto`-provided
      `gen_random_uuid()` (built into core since PostgreSQL 13):
Enter fullscreen mode Exit fullscreen mode
-- PostgreSQL 13+: core function, no extension needed
CREATE TABLE orders (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id;

-- PostgreSQL 12 and earlier: enable pgcrypto first
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- MySQL 8: UUID() is built in (v1-style, time + MAC based)
CREATE TABLE orders (
  id char(36) DEFAULT (UUID()),
  customer varchar(255) NOT NULL
);

-- MySQL 8.0.30+ also supports a v4 style via expression:
-- id binary(16) DEFAULT (UNHEX(REPLACE(UUID(), '-', '')))
Enter fullscreen mode Exit fullscreen mode
      Note the trade-off: MySQL's `UUID()` is a v1-style
      identifier (timestamp + hardware address), not a random v4, so it leaks
      creation time and MAC-derived bits. If your schema stores UUIDs as
      `char(36)`, that is 36 bytes per row versus 16 bytes in a
      `binary(16)` or PostgreSQL's native `uuid`
      type — meaningful on a billion-row table.
Enter fullscreen mode Exit fullscreen mode

Choosing Between UUID v4 and v7 for Primary Keys

      The classic objection to UUID primary keys is
      **index fragmentation**: a B-tree index expects roughly
      ordered keys, and purely random v4 values land on random pages, causing
      page splits, a bloated cache, and slow bulk inserts. UUID **v7**
      solves this by encoding a millisecond Unix timestamp in the top 48 bits,
      so identifiers arrive in creation order and insert at the right edge of
      the index — while keeping ~74 random bits for uniqueness:
Enter fullscreen mode Exit fullscreen mode
v4: 017d7f21-9db1-4a2e-a1b2-3c4d5e6f7a8b   fully random
v7: 018f6a2d-7c30-7xxx-yxxx-xxxxxxxxxxxx   starts with timestamp

Sorted lexicographically, v7 values line up with creation time;
v4 values shuffle. That ordering is what the index wants.
Enter fullscreen mode Exit fullscreen mode
      A practical decision rule: **use v7 when the UUID is a primary key
      in a relational database, v4 when it is an opaque token**. API keys,
      request IDs, and file names have no ordering requirement — v4 leaks
      nothing and never expires its usefulness. Row identifiers benefit from v7's
      insert locality and remain roughly sortable by eye in logs. One caution:
      v7 embeds creation time in the value itself, so anyone who can see the ID
      can tell *when* the record was created — irrelevant for most
      systems, but worth knowing before you mint them for anything timing-sensitive.
      (For a deeper dive, see our
      [
        UUID v4 vs v7 comparison
      ](https://devtoolshub.cloud/blog/uuid-v4-vs-v7)
      .)
Enter fullscreen mode Exit fullscreen mode

Batch Generation: When You Need Many UUIDs at Once

      Test fixtures, seed data, and CSV imports often need dozens of
      identifiers at once. Each platform has a loop one-liner, and for ad-hoc
      needs the browser tool saves the script entirely:
Enter fullscreen mode Exit fullscreen mode
// JavaScript: batch of 10
const ids = Array.from(, () => crypto.randomUUID());

# Python: batch of 10
import uuid
ids = [str(uuid.uuid4()) for _ in range(10)]

-- PostgreSQL: batch of 10 in one query
SELECT gen_random_uuid() FROM generate_series(1, 10);
Enter fullscreen mode Exit fullscreen mode
      For quick copy-paste needs — grabbing five UUIDs for a mock response, a
      dozen for a test config — the
      [
        UUID Generator
      ](https://devtoolshub.cloud/tools/uuid-generator)
      does it with one click and zero code.
Enter fullscreen mode Exit fullscreen mode

Common Mistakes & How to Avoid Them

      -
        **Calling crypto.randomUUID() on a non-secure page.** In
        browsers the method exists only on HTTPS and `localhost`.
        Serve over HTTP anywhere else and it is `undefined`. Keep the
        `getRandomValues` fallback from this article in shared code,
        and gate on `crypto.randomUUID` existing rather than on
        user-agent sniffing.


      -
        **Using Math.random() to build "UUIDs".**
        Template-string UUIDs from `Math.random()` are predictable
        and must never be used for session IDs, API keys, or anything
        security-sensitive. Use the cryptographic APIs above — they cost the
        same one line.


      -
        **Storing UUIDs as varchar when the DB has a native type.**
        PostgreSQL's `uuid` column type stores 16 bytes with
        built-in validation; `text` stores 37+ bytes per value and
        compares slower. In MySQL use `binary(16)` with
        `UUID_TO_BIN()`/`BIN_TO_UUID()` (MySQL 8+).


      -
        **Using random v4 as a clustered primary key at scale.**
        Random keys scatter across the B-tree, fragmenting indexes and slowing
        bulk inserts. For database row IDs prefer v7 (time-ordered), or keep an
        auto-increment internal key and expose the UUID as a public identifier.


      -
        **Minting one UUID and reusing it across records.** Copy-
        paste duplication in seed data silently merges unrelated rows through
        foreign keys. Generate fresh values per record — a loop, not a constant.
Enter fullscreen mode Exit fullscreen mode

Frequently Asked Questions

Is crypto.randomUUID() available in all browsers?

All current major browsers support it (Chrome 92+, Firefox 95+,
Safari 15.4+), but only in secure contexts: HTTPS pages and
localhost. On plain HTTP over a network the property is undefined.
Node.js exposes it since 14.17 without the secure-context rule. For
anything older or non-HTTPS, keep the crypto.getRandomValues
fallback shown above, which produces a standards-compliant v4 UUID.

Are UUIDs really unique?

Unique in practice, not in mathematics. A v4 UUID carries 122 random
bits, so the probability of a duplicate reaches 50 percent only
after generating about 2.7 quintillion values in the same system.
For perspective, a service minting a billion UUIDs per second would
run for over 85 years to get there. Collisions are theoretically
possible but so improbable that systems treat UUIDs as unique and
let a database constraint catch the astronomically unlikely case.

Should I use UUID or auto-increment as primary key?

Auto-increment integers are smaller (8 bytes vs 16), faster to
index, and naturally ordered, which is why they remain the default
for single-database systems. UUIDs earn their place when IDs are
generated outside the database (mobile clients, multiple services,
offline writes), when IDs must be unguessable in URLs, or when you
merge data from shards that would produce overlapping integer keys.
A common hybrid: internal auto-increment key plus a UUID column for
external references.

What is the difference between UUID v4 and v7?

v4 is 122 purely random bits: no structure, no ordering, nothing
leaked. v7 embeds a 48-bit millisecond Unix timestamp in the
leading bits, followed by random bits, so v7 values sort in
creation order. That ordering gives v7 better B-tree insert
locality, which is why it is increasingly preferred for database
primary keys, while v4 remains ideal for opaque tokens such as API
keys and request IDs. v7 also reveals creation time by design.

Can I generate many UUIDs at once?

Yes, in one line everywhere: an Array.from call mapping
crypto.randomUUID() in JavaScript, a list comprehension
over uuid.uuid4() in Python, or SELECT gen_random_uuid() FROM
generate_series(1, N) in PostgreSQL. For a no-code option, our
UUID Generator
produces bulk lists with one click, entirely in the browser.

        **Related Tools:**
        [UUID Generator](https://devtoolshub.cloud/tools/uuid-generator)

        [JSON Formatter](https://devtoolshub.cloud/tools/json-formatter)

        [Base64 Encoder / Decoder](https://devtoolshub.cloud/tools/base64)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)