Skip to content

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.

← Developer Zone
Updated: 2026-03-22

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.

Use this for generation, not architecture

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.

Match the runtime exactly

Pick browser, CLI, backend, or runtime-specific code so you do not import the wrong dependency or API.

Review ordering and persistence assumptions

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.

Languages

13

Related tools

3

Topics

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.

Bash
Check notes

Review the notes for setup details.

C#
Check notes

Review the notes for setup details.

Delphi
Check notes

Review the notes for setup details.

Go
External

go get github.com/google/uuid

Java
Check notes

Review the notes for setup details.

JavaScript
Check notes

Review the notes for setup details.

Kotlin
Check notes

Review the notes for setup details.

PHP
Check notes

Review the notes for setup details.

Python
Check notes

Review the notes for setup details.

Ruby
Check notes

Review the notes for setup details.

Rust
External

uuid = { version = "1", features = ["v4"] }

TypeScript
Check notes

Review the notes for setup details.

VB.NET
Check notes

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.

1. Start with the problem

Make sure the article really matches the issue you are debugging before copying code just because the title looks close.

2. Read the notes

That is where portability limits, dependency requirements, and runtime assumptions usually appear.

3. Validate the output

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

bash
Bash
uuidgen || cat /proc/sys/kernel/random/uuid
Explanation

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.

Notes
  • macOS/Linux.
  • On Windows, use PowerShell or a system tool.
  • Do not rely on this inside minimal containers without /proc.

C#

csharp
C#
using System;

Console.WriteLine(Guid.NewGuid());
Explanation

In .NET, Guid.NewGuid() generates a UUID v4. This is the standard way to create unique ids with no external dependencies.

Notes
  • Works with modern .NET (top-level statements).
  • Useful for technical ids, correlation ids, and tests.

Delphi

delphi
Delphi
program UuidV4;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

var
  G: TGUID;

begin
  CreateGUID(G);
  Writeln(GUIDToString(G));
end.
Explanation

CreateGUID generates a GUID/UUID, and GUIDToString returns it in standard format. It is a simple, common approach in Delphi.

Notes
  • Requires System.SysUtils.
  • Output may include braces depending on GUIDToString; normalize if you need no braces.

Go

go
Go
package main

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

func main() {
  fmt.Println(uuid.New())
}
Explanation

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().

Notes
  • Dependency: go get github.com/google/uuid
  • Useful in Go CLIs and services when you need coordination-free ids.

Java

java
Java
import java.util.UUID;

public class Main {
  public static void main(String[] args) {
    System.out.println(UUID.randomUUID());
  }
}
Explanation

UUID.randomUUID() generates a UUID v4 with no external dependencies. It is the standard way in Java.

Notes
  • Available in Java SE (java.util.UUID).
  • In web apps, generate ids in the backend for persistent resources.

JavaScript

javascript
JavaScript
import { randomUUID } from "node:crypto";

console.log(randomUUID());
Explanation

In Node.js you can generate UUID v4 using randomUUID() from the crypto module. It is fast and requires no dependencies.

Notes
  • Node.js (ESM). In modern browsers you can use crypto.randomUUID().
  • Avoid rolling your own UUID with Math.random.

Kotlin

kotlin
Kotlin
import java.util.UUID

fun main() {
  println(UUID.randomUUID().toString())
}
Explanation

In Kotlin (JVM), use java.util.UUID. UUID.randomUUID() generates a standard UUID v4.

Notes
  • Kotlin/JVM.
  • For multiplatform, the approach depends on your target (JVM/JS/Native).

PHP

php
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;
Explanation

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.

Notes
  • Requires PHP with random_bytes() (PHP 7+).
  • If you use Composer on backend, ramsey/uuid is a popular alternative.

Python

python
Python
import uuid

print(uuid.uuid4())
Explanation

uuid.uuid4() generates a UUID v4 using the standard library. This is the recommended approach for scripts, CLIs, and backend.

Notes
  • Available in standard Python.
  • When serializing to JSON, convert to string.

Ruby

ruby
Ruby
require "securerandom"

puts SecureRandom.uuid
Explanation

SecureRandom.uuid generates a standard UUID v4 using Ruby standard library.

Notes
  • Available in standard Ruby.
  • Great for scripts, seeds, fixtures, and log correlation.

Rust

rust
Rust
use uuid::Uuid;

fn main() {
  println!("{}", Uuid::new_v4());
}
Explanation

Rust does not include UUID generation in std. With the uuid crate you can generate UUID v4 using Uuid::new_v4().

Notes
  • Dependency: uuid = { version = "1", features = ["v4"] }
  • Ensure an appropriate RNG via crate features.

TypeScript

ts
TypeScript
import { randomUUID } from "node:crypto";

console.log(randomUUID());
Explanation

In TypeScript for Node, randomUUID() is the most direct option. In browsers, the modern equivalent is crypto.randomUUID().

Notes
  • 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

vbnet
VB.NET
Imports System

Module Program
  Sub Main()
    Console.WriteLine(Guid.NewGuid().ToString())
  End Sub
End Module
Explanation

In VB.NET you use the same .NET Guid type. Guid.NewGuid() generates UUID v4 with no dependencies.

Notes
  • 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.