Question
How can I create GUIDs (globally unique identifiers) in JavaScript?
The GUID or UUID should be at least 32 characters long and remain within the ASCII character range so it can be passed around safely.
I am also unsure which routines are available across browsers, how random the built-in number generator is, and whether it is suitable for this purpose.
Short Answer
By the end of this page, you will understand what GUIDs and UUIDs are, how they are usually generated in JavaScript, why randomness quality matters, and which browser-safe APIs to prefer. You will also learn practical patterns for generating UUIDs in modern JavaScript and what to avoid when using Math.random().
Concept
A GUID (Globally Unique Identifier) and UUID (Universally Unique Identifier) are identifiers designed to be unique across systems, sessions, devices, and time.
In JavaScript, developers usually mean a UUID string, often in the standard version 4 format, such as:
550e8400-e29b-41d4-a716-446655440000
This format:
- uses only ASCII characters
- is 36 characters long including hyphens
- contains 32 hexadecimal characters
- is commonly used in APIs, databases, frontend state, and distributed systems
Why uniqueness matters
Unique identifiers are useful when:
- creating IDs for client-side objects
- tagging requests or logs
- generating keys for temporary records
- correlating events across systems
- avoiding collisions when many users or devices create data independently
Why Math.random() is not ideal
A common beginner approach is to build a UUID-like string using Math.random(). That may look random, but it is not cryptographically secure and can vary in quality across environments.
Problems with Math.random() for IDs:
- it is not designed for security-sensitive randomness
- implementations differ between engines
- collisions are more likely than with cryptographic randomness
- it may be predictable in some contexts
What to use instead
In modern JavaScript, the preferred option is the Web Crypto API:
crypto.randomUUID()generates a standard UUID directlycrypto.getRandomValues()provides secure random bytes if you need a custom format
These APIs are designed for better randomness and are the correct choice when generating unique tokens in browsers and modern JavaScript runtimes.
GUID vs UUID
In everyday JavaScript usage, people often use the terms interchangeably. Technically:
- UUID is the broader standard term
- GUID is a term popularized by Microsoft
For most web development discussions, treating them as the same kind of identifier is fine.
Mental Model
Think of a UUID like a pre-printed luggage tag at a huge airport.
- Every bag needs a label.
- The label must be different enough that two bags do not get confused.
- The label uses a simple character set so machines everywhere can read it.
If you create labels by guessing with a weak random process, eventually two bags may get similar labels or the process may be predictable.
If you use a reliable machine designed to create unique labels, the chance of accidental collision becomes extremely small.
In JavaScript, crypto.randomUUID() is that reliable machine.
Syntax and Examples
Modern best option: crypto.randomUUID()
If your environment supports it, this is the simplest and best choice:
const id = crypto.randomUUID();
console.log(id);
// Example: "3f29c5e2-9d6d-4d9c-a2bf-7c9f5f77d0b1"
Why this is good
- produces a standard UUID v4
- uses secure randomness
- ASCII-safe output
- easy to read and store
Custom UUID-like string using crypto.getRandomValues()
If randomUUID() is unavailable, you can generate secure random bytes and convert them to hexadecimal:
function generateHexId() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, byte =>
byte.toString(16).padStart(2, )
).();
}
id = ();
.(id);
Step by Step Execution
Consider this example:
function generateHexId() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, byte =>
byte.toString(16).padStart(2, '0')
).join('');
}
const id = generateHexId();
console.log(id);
Here is what happens step by step:
new Uint8Array(16)creates an array of 16 bytes.- Each byte can store a number from
0to255. crypto.getRandomValues(bytes)fills all 16 bytes with secure random values.Array.from(bytes, ...)loops over each byte.byte.toString(16)converts each number to hexadecimal.
Real World Use Cases
Client-side temporary IDs
When a user creates a note, todo, or form entry before saving to the server, you can assign a UUID locally.
Correlation IDs for logs
A frontend app can attach a UUID to a request so logs across frontend, backend, and monitoring systems can be matched.
Database record identifiers
Some systems use UUIDs instead of auto-incrementing integers to avoid exposing record counts or to support distributed creation.
File or upload tracking
A browser app can generate a unique ID for each upload session.
Offline-first applications
If users can create records while offline, UUIDs let multiple devices create unique records without needing a central server first.
API idempotency keys
A client can generate a unique ASCII-safe token to prevent duplicate API actions, such as repeated payment or order requests.
Real Codebase Usage
In real projects, developers usually do not generate UUIDs manually unless they need a special format.
Common patterns
Use built-in APIs first
const id = crypto.randomUUID();
This is the most readable option.
Fallback when needed
function createId() {
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
return crypto.randomUUID();
}
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
}
Validation before use
Developers often check that an incoming ID has the expected shape.
Common Mistakes
1. Using Math.random() for important IDs
Broken example:
function badUuid() {
return Math.random().toString(16).slice(2);
}
Why it is a problem:
- not cryptographically secure
- output length can vary
- easier to collide than proper UUID generation
Use crypto.randomUUID() or crypto.getRandomValues() instead.
2. Assuming all random strings are UUIDs
Broken example:
const id = 'abc123';
This is just a string, not a standard UUID. If your system expects UUID format, generate or validate accordingly.
3. Forgetting ASCII-safe encoding rules
If you generate raw bytes and try to store them directly as text, the result may contain non-printable characters.
Broken example:
const bytes = ();
crypto.(bytes);
text = .(...bytes);
Comparisons
Common approaches compared
| Approach | Example output | Secure randomness | Standard format | ASCII-safe | Recommended |
|---|---|---|---|---|---|
crypto.randomUUID() | 3f29c5e2-9d6d-4d9c-a2bf-7c9f5f77d0b1 | Yes | Yes | Yes | Yes |
crypto.getRandomValues() + hex | 9f3c1b2e7a4d8c0f11aa22bb33cc44dd | Yes | Not automatically | Yes | Yes |
Math.random() string | a13bf09c | No |
Cheat Sheet
Quick reference
Best modern option
const id = crypto.randomUUID();
Generate a 32-character hex ID
function generateHexId() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
}
Rules to remember
- UUIDs are usually represented as hex strings.
- Standard UUID v4 format is 36 characters including hyphens.
- Hex-only IDs are ASCII-safe.
- Prefer
crypto.randomUUID()when available. - Use
crypto.getRandomValues()for secure custom formats. - Avoid
Math.random()when uniqueness matters.
Standard UUID pattern
FAQ
What is the difference between a GUID and a UUID?
In most JavaScript discussions, they are treated as the same idea: a unique identifier string. UUID is the standard term, while GUID is a commonly used name from Microsoft ecosystems.
Can I use Math.random() to generate a UUID in JavaScript?
You can create a random-looking string with it, but it is not the recommended choice when uniqueness matters. Use crypto.randomUUID() or crypto.getRandomValues() instead.
Is crypto.randomUUID() supported in browsers?
It is supported in modern environments. If you need wider compatibility or a custom format, use crypto.getRandomValues().
Why are UUIDs often written with hyphens?
That is the common textual representation of the standard UUID format. The hyphens improve readability but are not the source of uniqueness.
How long is a UUID in JavaScript?
A standard UUID string is 36 characters long, including hyphens, or 32 hexadecimal characters without them.
Are UUIDs guaranteed to be unique?
Not absolutely, but properly generated UUIDs have an extremely low chance of collision and are considered safe for most applications.
Can I generate a UUID without a library?
Yes. In modern JavaScript, you can use built-in crypto APIs directly.
Should I store UUIDs as strings?
Yes, that is common and practical, especially when sending them through APIs, logging them, or storing them in JSON.
Mini Project
Description
Build a small JavaScript utility that creates safe unique IDs for client-side records. This mirrors a common real-world need: creating IDs for notes, tasks, uploads, or offline data before the server assigns a permanent identifier.
Goal
Create a reusable ID generator that returns either a standard UUID or a 32-character hexadecimal ID using secure browser APIs.
Requirements
- Create a function that returns a standard UUID when
crypto.randomUUID()is available. - Add a fallback that generates a 32-character hexadecimal ID using
crypto.getRandomValues(). - Ensure the result contains only ASCII-safe characters.
- Generate and print several example IDs.
- Add a simple validation check for UUID-shaped strings.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.