How to generate a UUID v4 (copy/paste snippets)
Practical guide to generate UUID v4 across languages. Includes real snippets, compatibility notes, and dependencies when needed.
Use this article when...
This section is built for speed: one concrete task, multiple stacks, and the minimum context needed not to copy the wrong thing.
These snippets are great when you need an id now. They do not decide whether UUID v4 is the right identifier model for your system.
Pick browser, CLI, backend, or runtime-specific code so you do not import the wrong dependency or API.
If the id needs sortability or database semantics, stop and review those constraints before choosing the snippet.
What this article gives you
A short path from incident to implementation: context, language-specific snippets, and the warning signs that usually get skipped.
13
3
uuid, ids, backend, frontend, testing
UUID v4 is a random identifier (RFC 4122) you can generate without central coordination. It is great for tests, mock data, log correlation, and temporary client-side ids.
Practical rule: generate UUIDs where you need them (frontend or backend) and avoid using them as “sortable ids”. If you need ordering, combine UUID with createdAt or use sortable ids.
Dependency snapshot by language
Check this first to see which snippets use built-in/runtime APIs and which ones need external packages before you start copying code.
Review the notes for setup details.
Review the notes for setup details.
Review the notes for setup details.
go get github.com/google/uuid
Review the notes for setup details.
Review the notes for setup details.
Review the notes for setup details.
Review the notes for setup details.
Review the notes for setup details.
Review the notes for setup details.
uuid = { version = "1", features = ["v4"] }
Review the notes for setup details.
Review the notes for setup details.
How to use these code examples well
The snippet is only the fast path. The explanation and notes are what keep you from copying the wrong assumption into production.
Make sure the article really matches the issue you are debugging before copying code just because the title looks close.
That is where portability limits, dependency requirements, and runtime assumptions usually appear.
If the code runs but the bug remains, jump to the related tool and inspect the real payload, token, timestamp, or config.
Code examples by language
Snippets that compile/run, plus short explanations and real-world notes.
Bash
uuidgen || cat /proc/sys/kernel/random/uuid
Generates a UUID v4 from the CLI. On macOS, uuidgen is usually available. On Linux, when uuidgen is not installed, the kernel exposes a UUID via /proc.
- macOS/Linux.
- On Windows, use PowerShell or a system tool.
- Do not rely on this inside minimal containers without /proc.
C#
using System;
Console.WriteLine(Guid.NewGuid());
In .NET, Guid.NewGuid() generates a UUID v4. This is the standard way to create unique ids with no external dependencies.
- Works with modern .NET (top-level statements).
- Useful for technical ids, correlation ids, and tests.
Delphi
program UuidV4;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
G: TGUID;
begin
CreateGUID(G);
Writeln(GUIDToString(G));
end.
CreateGUID generates a GUID/UUID, and GUIDToString returns it in standard format. It is a simple, common approach in Delphi.
- Requires System.SysUtils.
- Output may include braces depending on GUIDToString; normalize if you need no braces.
Go
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
fmt.Println(uuid.New())
}
Go does not include UUID generation in the standard library. A common option is github.com/google/uuid, which generates UUID v4 with uuid.New().
- Dependency: go get github.com/google/uuid
- Useful in Go CLIs and services when you need coordination-free ids.
Java
import java.util.UUID;
public class Main {
public static void main(String[] args) {
System.out.println(UUID.randomUUID());
}
}
UUID.randomUUID() generates a UUID v4 with no external dependencies. It is the standard way in Java.
- Available in Java SE (java.util.UUID).
- In web apps, generate ids in the backend for persistent resources.
JavaScript
import { randomUUID } from "node:crypto";
console.log(randomUUID());
In Node.js you can generate UUID v4 using randomUUID() from the crypto module. It is fast and requires no dependencies.
- Node.js (ESM). In modern browsers you can use crypto.randomUUID().
- Avoid rolling your own UUID with Math.random.
Kotlin
import java.util.UUID
fun main() {
println(UUID.randomUUID().toString())
}
In Kotlin (JVM), use java.util.UUID. UUID.randomUUID() generates a standard UUID v4.
- Kotlin/JVM.
- For multiplatform, the approach depends on your target (JVM/JS/Native).
PHP
<?php
$bytes = random_bytes(16);
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
$hex = bin2hex($bytes);
$uuid = sprintf('%s-%s-%s-%s-%s',
substr($hex, 0, 8),
substr($hex, 8, 4),
substr($hex, 12, 4),
substr($hex, 16, 4),
substr($hex, 20, 12)
);
echo $uuid . PHP_EOL;
Generates a UUID v4 without external libraries: random_bytes() provides secure entropy, then you set version (4) and variant (RFC 4122) and format as hex.
- Requires PHP with random_bytes() (PHP 7+).
- If you use Composer on backend, ramsey/uuid is a popular alternative.
Python
import uuid
print(uuid.uuid4())
uuid.uuid4() generates a UUID v4 using the standard library. This is the recommended approach for scripts, CLIs, and backend.
- Available in standard Python.
- When serializing to JSON, convert to string.
Ruby
require "securerandom"
puts SecureRandom.uuid
SecureRandom.uuid generates a standard UUID v4 using Ruby standard library.
- Available in standard Ruby.
- Great for scripts, seeds, fixtures, and log correlation.
Rust
use uuid::Uuid;
fn main() {
println!("{}", Uuid::new_v4());
}
Rust does not include UUID generation in std. With the uuid crate you can generate UUID v4 using Uuid::new_v4().
- Dependency: uuid = { version = "1", features = ["v4"] }
- Ensure an appropriate RNG via crate features.
TypeScript
import { randomUUID } from "node:crypto";
console.log(randomUUID());
In TypeScript for Node, randomUUID() is the most direct option. In browsers, the modern equivalent is crypto.randomUUID().
- Node.js (ESM). Adjust module/target based on your build.
- If the id goes to DB, generate it in the backend and validate inputs.
VB.NET
Imports System
Module Program
Sub Main()
Console.WriteLine(Guid.NewGuid().ToString())
End Sub
End Module
In VB.NET you use the same .NET Guid type. Guid.NewGuid() generates UUID v4 with no dependencies.
- Works on .NET Framework and modern .NET.
- Useful for internal tools and console scripts.
Related tools
Use the tool when you need to generate or validate output fast.
Trust and privacy
Copy/paste-friendly by design. Still, treat real production secrets carefully.
- Prefer synthetic examples when sharing screens or recording.
- Do not paste real API keys, tokens, or personal data unless you fully trust your environment.
- If you need ordering, do not use UUID v4 as a sortable id: add createdAt or use sortable ids.