Web Development

Can I generate UUIDs in different programming languages?

A one-line UUID cheat sheet for every major language — Python, JavaScript, Node, Java, Go, Rust, C#, PHP, Ruby, and SQL — plus which calls are built in, which need a package, and where the new time-ordered UUIDv7 lives.

By Inventive HQ Team

Every mainstream language can generate a UUID in a single line, and in most of them it is built into the standard library — no dependency required. The default result is a version 4 (random) UUID: crypto.randomUUID() in JavaScript and Node.js, uuid.uuid4() in Python, UUID.randomUUID() in Java, Guid.NewGuid() in C#/.NET, uuid.New() in Go (via google/uuid), Uuid::new_v4() in Rust (via the uuid crate), SecureRandom.uuid in Ruby, Uuid::uuid4() in PHP (via ramsey/uuid), and gen_random_uuid() in PostgreSQL. Every one produces the same 128-bit, 36-character identifier defined by RFC 9562 — for example 550e8400-e29b-41d4-a716-446655440000 — so a UUID minted in one language is valid, parseable, and comparable in every other.

That is the summary an AI overview gives you. What it can't tell you at a glance is which of those calls are truly built in versus a package you must install, why crypto.randomUUID() quietly returns undefined on an http:// page, and which languages have caught up to UUIDv7 — the new time-ordered version that is rapidly becoming the right default for database keys. The rest of this article is the cheat sheet plus those gotchas.

Generate one right now

Before the code, here is a live generator — pick a version, copy the value, and use the snippets below to reproduce it in your language of choice.

Loading interactive tool...

The one-line cheat sheet (every major language)

This is the reference table. The call column is the shortest idiomatic way to get a random UUID; the v7 column shows how to get the newer time-ordered variant where it exists.

LanguageOne-line call (v4 random)Built-in or packageTime-ordered v7
Pythonuuid.uuid4()Built-in (uuid stdlib)uuid.uuid7() — Python 3.14+
JavaScript (browser)crypto.randomUUID()Built-in (Web Crypto)uuidv7 npm package
Node.jscrypto.randomUUID()Built-in since v14.17crypto.randomUUIDv7() (experimental)
JavaUUID.randomUUID()Built-in (java.util)Library (e.g. java-uuid-generator)
C# / .NETGuid.NewGuid()Built-in (System)Guid.CreateVersion7() — .NET 9+
Gouuid.New()Package github.com/google/uuiduuid.NewV7()
RustUuid::new_v4()Crate uuid (feature v4)Uuid::now_v7() (feature v7)
PHPUuid::uuid4()Package ramsey/uuidUuid::uuid7()
RubySecureRandom.uuidBuilt-in (securerandom)Gem (e.g. uuid7)
SQL (PostgreSQL)gen_random_uuid()Built-in (PG 13+)uuidv7() — PG 18+
SQL (SQL Server)NEWID()Built-inNEWSEQUENTIALID() (sequential GUID)

Which should you reach for? If you only need a unique ID, the built-in v4 call in your language is the correct answer — do not add a dependency. Reach for v7 specifically when the UUID becomes a database primary key, where its leading timestamp keeps rows insert-ordered and avoids index bloat.

Anatomy of the value they all return

Every call above emits the same structure. Two nibbles are not random — they encode the version and the variant, which is how any parser can read a raw string and tell you it is a "v4" UUID.

Anatomy of a UUID string The 36-character UUID 550e8400-e29b-41d4-a716-446655440000 split into its five hyphen-separated groups, highlighting the version digit 4 and the variant digit a. One format, every language: the 128-bit UUID 32 hex digits, grouped 8-4-4-4-12, defined by RFC 9562

550e8400 - e29b -

4 1d4 -

a 716 - 446655440000

version = 4 (random) variant = a (RFC 9562) 8, 9, a, or b

The other 122 bits carry the randomness — 5.3 x 10^36 possible v4 values.

JavaScript and TypeScript

Browser: modern browsers expose native UUID generation through the Web Crypto API:

// Version 4 (random) UUID — no library needed
const uuid = crypto.randomUUID();
console.log(uuid); // e.g. "550e8400-e29b-41d4-a716-446655440000"

The one gotcha: crypto.randomUUID() is only defined in a secure context (HTTPS or localhost). On a plain http:// page it is undefined — if you support insecure origins, fall back to the uuid package.

Node.js: the same call works, built in since Node 14.17:

import { randomUUID } from 'node:crypto';

const id = randomUUID();      // v4
console.log(id);

// Time-ordered v7 (experimental) in recent Node:
import { randomUUIDv7 } from 'node:crypto'; // guard: may be undefined on older runtimes

For versioned or namespaced UUIDs (v3/v5) or a stable v7 across runtimes, use the uuid package:

import { v4 as uuidv4, v5 as uuidv5, v7 as uuidv7 } from 'uuid';

const random = uuidv4();
const stable = uuidv5('example.com', uuidv5.DNS); // deterministic
const sortable = uuidv7();                          // time-ordered

TypeScript uses the identical APIs; crypto.randomUUID() is typed as returning a branded template-literal string (${string}-${string}-...), so you get compile-time shape checking for free.

Advertisement

Python

Python's standard-library uuid module covers every classic version with zero dependencies:

import uuid

random_uuid = uuid.uuid4()                       # v4 (random) — the default
time_uuid   = uuid.uuid1()                        # v1 (time + node)
name_uuid   = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')  # v5 (deterministic)

parsed = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')   # string -> UUID

# Python 3.14+ adds the draft versions to the stdlib:
sortable = uuid.uuid7()  # time-ordered, ideal for DB keys

Before Python 3.14, get v6/v7/v8 from the uuid-utils package (a Rust-backed drop-in). For everything else, uuid.uuid4() is all you need.

Java

Java has built-in UUID support in java.util.UUID:

import java.util.UUID;

UUID randomUuid = UUID.randomUUID();  // v4 (random)
UUID parsed = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");

int version = randomUuid.version();   // 4
int variant = randomUuid.variant();   // 2 (RFC 9562/4122 layout)

Note UUID.nameUUIDFromBytes(...) produces a v3 (MD5) name-based UUID, not v5. The JDK has no built-in v7; use a library such as com.fasterxml.uuid:java-uuid-generator for time-ordered IDs.

C# and .NET

C#/.NET uses the Guid struct (GUID is Microsoft's name for a UUID):

using System;

Guid newGuid = Guid.NewGuid();                    // v4 (random)
Guid parsed = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");
Guid empty  = Guid.Empty;                          // all-zero UUID

string noHyphens = newGuid.ToString("N");          // 32 chars, no dashes

// .NET 9+ adds native time-ordered v7:
Guid v7 = Guid.CreateVersion7();

Go

Go's de-facto standard is the github.com/google/uuid package:

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id := uuid.New()                 // v4 (random), panics on RNG failure
    id4, _ := uuid.NewRandom()       // v4, returns an error instead of panicking
    id7, _ := uuid.NewV7()           // v7 (time-ordered)

    parsed, _ := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
    fmt.Println(id, id4, id7, parsed)
}

Install with go get github.com/google/uuid.

Rust

Rust's uuid crate is gated behind feature flags — enable the versions you use:

# Cargo.toml
uuid = { version = "1", features = ["v4", "v7"] }
use uuid::Uuid;

let id = Uuid::new_v4();     // v4 (random)
let id7 = Uuid::now_v7();    // v7 (time-ordered)

let parsed = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
println!("{id} {id7} {parsed}");

PHP

PHP has no built-in UUID generator; ramsey/uuid is the standard choice (composer require ramsey/uuid):

<?php
require 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;

$v4 = Uuid::uuid4();                                  // random
$v5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com'); // deterministic
$v7 = Uuid::uuid7();                                  // time-ordered

echo $v4->toString();  // e.g. 550e8400-e29b-41d4-a716-446655440000

Ruby

Ruby's standard library covers v4 through SecureRandom:

require 'securerandom'

uuid = SecureRandom.uuid   # v4 (random), no gem required
puts uuid

SecureRandom.uuid only returns v4. For v7 or name-based UUIDs, add a gem such as uuid7.

SQL (generate them in the database)

You often want the database itself to mint the key:

-- PostgreSQL 13+ (built in, random v4)
SELECT gen_random_uuid();

-- PostgreSQL 18+ (native time-ordered v7)
SELECT uuidv7();

-- SQL Server (random GUID)
SELECT NEWID();
-- ... or sequential, better for clustered index inserts:
-- DEFAULT NEWSEQUENTIALID()

-- MySQL 8 (note: UUID() returns a v1 UUID)
SELECT UUID();

Store UUID keys in a native uuid column (Postgres) or 16-byte BINARY(16) (MySQL/SQL Server) rather than a 36-char string — it halves the storage and speeds up index comparisons.

UUID versions: which one, and when

VersionHow it is builtSortable?Use it for
v1Timestamp + MAC/nodeBy timeLegacy systems; avoid in new code (leaks MAC)
v4122 random bitsNoThe safe default for general unique IDs
v5SHA-1 of namespace + nameNoDeterministic IDs (same input → same UUID)
v7Unix-ms timestamp + randomBy timeDatabase primary keys — the modern best choice

The headline shift since RFC 9562 (2024) is v7. A random v4 primary key scatters inserts all over a B-tree index, causing page splits and fragmentation; v7's leading millisecond timestamp keeps new rows appending to the "end" of the index, the way an auto-increment key would — while still being globally unique and non-coordinated. If you are choosing a key type for a new table today, v7 is usually the answer; v4 remains right for opaque tokens and IDs you do not want to reveal a creation time.

Best practices

  1. Default to the built-in v4 call. Do not add a dependency to generate a random ID when your standard library already does it (Python, Java, C#, Ruby, Node, browsers, Postgres).
  2. Use v7 for database primary keys so inserts stay index-friendly; use v4 for tokens where a leaked timestamp would matter.
  3. Use v5 for deterministic IDs — when the same input must always map to the same UUID.
  4. Avoid v1 in new code because it can embed the machine's MAC address (a privacy and enumeration risk).
  5. Store as 16 bytes, not 36 characters — native uuid/BINARY(16) columns are smaller and index faster than text.
  6. Validate on input before trusting a UUID from an untrusted source:
const UUID_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const isValidUUID = (s) => UUID_RE.test(s);

UUID vs other identifier schemes

  • vs database sequences — UUIDs need no central coordinator, so any node can mint one offline; sequences are shorter and human-readable but require a single source of truth. Use UUIDs for distributed systems, sequences for a single database.
  • vs ULIDs — ULIDs are also time-sortable and use Crockford base32 (26 chars, URL-friendly). UUIDv7 now covers the same "sortable ID" need while staying in the standard UUID format, so it is the more portable choice.
  • vs Snowflake IDs — 64-bit, coordinated IDs tuned for extreme insert rates at Twitter/Discord scale. UUIDs are 128-bit and need no ID-allocation service, which makes them simpler for almost every other system.

Conclusion

UUID generation is a solved, one-line problem in every major language — usually built into the standard library, and always producing the same RFC 9562 format so the value travels freely between systems. Reach for the built-in v4 call by default, switch to v7 when the UUID is a database key, and use v5 when you need determinism. The APIs differ; the 128-bit identifier they hand you does not.

Frequently Asked Questions

How do I generate a UUID in JavaScript?

Call the built-in crypto.randomUUID(). It returns a version 4 (random) UUID string and works in modern browsers and in Node.js 14.17 and newer, with no library required. The one catch in the browser: crypto.randomUUID() only exists in a secure context, meaning HTTPS or localhost. On a plain http:// page it will be undefined, in which case fall back to the npm uuid package.

What is the easiest way to generate a UUID in Python?

Import the standard library uuid module and call uuid.uuid4(). It needs no external dependency and returns a random version 4 UUID. The same module also gives you uuid1() (time-based), uuid3()/uuid5() (name-based), and, as of Python 3.14, uuid6(), uuid7(), and uuid8() for the newer draft versions.

Do all programming languages produce the same UUID format?

Yes. Every language follows RFC 9562 (which replaced RFC 4122 in 2024), so a UUID is always a 128-bit value written as 32 hexadecimal digits in the 8-4-4-4-12 grouping, for example 550e8400-e29b-41d4-a716-446655440000. A UUID generated in Python is byte-for-byte valid in Java, Go, C#, or a Postgres uuid column. Only the API call differs between languages, never the result format.

Is crypto.randomUUID() the modern standard for generating UUIDs?

For version 4 UUIDs in JavaScript and Node.js, yes. crypto.randomUUID() is part of the Web Crypto API, is cryptographically secure, and has replaced the older habit of pulling in the uuid npm package just to make a random ID. It does not generate other versions, though: for the time-ordered UUIDv7 you need Node's experimental crypto.randomUUIDv7() or a library such as uuidv7.

Which UUID version should I use?

Use version 4 (random) as the default for general-purpose unique IDs — it is unpredictable and available everywhere. Use version 7 (time-ordered) when the UUID is a database primary key, because its leading timestamp keeps inserts sequential and avoids the index fragmentation that random v4 keys cause. Use version 5 (name-based) when you need the same input to always produce the same UUID. Avoid version 1 in new code because it can embed the machine's MAC address.

How do I generate a UUID in SQL?

In PostgreSQL 13 and newer, gen_random_uuid() returns a random v4 UUID with no extension needed, and PostgreSQL 18 adds a native uuidv7() function. In SQL Server, NEWID() returns a random GUID, while NEWSEQUENTIALID() returns sequential values that index better. In MySQL, UUID() returns a version 1 UUID.

What is UUIDv7 and which languages support it?

UUIDv7 is a UUID whose first 48 bits are a Unix-millisecond timestamp, making the IDs sortable by creation time while the remaining bits stay random. That time-ordering makes it far better than v4 as a database key. Support is now broad: Python 3.14 (uuid7), Node.js (experimental crypto.randomUUIDv7), Go's google/uuid (NewV7), the Rust uuid crate (now_v7), .NET 9 (Guid.CreateVersion7), PHP's ramsey/uuid (uuid7), and PostgreSQL 18 (uuidv7).

Are UUIDs guaranteed to be unique?

Not guaranteed in the absolute sense, but the collision probability for random v4 UUIDs is so small it is treated as zero in practice. There are 2^122 possible v4 values; you would need to generate roughly 2.7 quintillion of them before there is even a one-in-a-billion chance of a single collision. That is why applications generate UUIDs independently, without a central authority, and never check for duplicates.

UUIDidentifier generationprogramming languagesdevelopmentbest practices
Advertisement