How to Generate a UUID in JavaScript, Python, and Go

All three of these languages can generate a cryptographically random version 4 UUID without pulling in a third-party package, which surprises people who remember needing a library for this a few years back. Here is the shortest correct way to do it in each one, plus a note on when you would still reach for a library instead.

JavaScript (browser or Node.js 19+)

const id = crypto.randomUUID();
// e.g. "f47ac10b-58cc-4372-a567-0e02b2c3d479"

crypto.randomUUID() is a built-in Web Crypto API method, available in every modern browser and in Node.js from version 19 onward, or 14.17 and later behind the crypto module import. No dependency needed. If you are stuck on an older Node version without it, the widely used uuid npm package is the standard fallback.

Python 3.7+

import uuid
id = uuid.uuid4()
print(str(id))
# e.g. "f47ac10b-58cc-4372-a567-0e02b2c3d479"

The uuid module has been part of Python's standard library for a long time, and uuid4() is the function that produces a random version 4 identifier. No pip install required. The same module also gives you uuid1() for timestamp-based ids and uuid5() for deterministic, namespace-based ids if you need either of those instead.

Go

Go's standard library does not include a UUID generator directly, which is the one exception here. The community standard is google/uuid, which is well maintained and what most production Go codebases use:

import "github.com/google/uuid"

id := uuid.New()
fmt.Println(id.String())
// e.g. "f47ac10b-58cc-4372-a567-0e02b2c3d479"

uuid.New()generates a random version 4 UUID and panics only in the extraordinarily rare case that the system's random source fails, which in practice never happens on a normally functioning machine. If you would rather handle that error explicitly instead of allowing a panic, uuid.NewRandom() returns an error value you can check instead.

When you would still reach for a library

The built-in options above are all backed by proper cryptographically secure randomness, so there is no security reason to add a dependency just for basic v4 generation. Where a library still earns its keep is validation (checking whether an arbitrary string is a well-formed UUID), parsing UUIDs out of other formats, or generating v1 and v5 identifiers in languages whose standard library does not cover those versions.

Testing output without writing any code

If you just need a batch of ids right now, without touching a terminal, the GUID Generator on this site generates v1, v4, and v5 UUIDs in bulk, entirely in your browser, in either hyphenated or compact format.

← Back to KeyForge