Logo
⚠️ Unsaved
[M]:

UUID: Generating Unique Identifiers

Need to create unique IDs that won't collide even across distributed systems? UUIDs (Universally Unique Identifiers) are your answer. In this notebook, we'll explore how to generate and work with UUIDs in JavaScript, the different versions available, and when to use each one.

Let's dive into the world of unique identifiers and see how they can solve common problems in web development, databases, and distributed systems.

[1]:
// Install the uuid package
!npm install uuid
$ npm install uuid

added 1 package in 2s

29 packages are looking for funding
  run `npm fund` for details
[M]:

What Are UUIDs?

UUIDs (also known as GUIDs - Globally Unique Identifiers) are 128-bit identifiers that are designed to be unique across space and time. They look like this: 123e4567-e89b-12d3-a456-426614174000.

The chance of generating duplicate UUIDs is so astronomically low that for practical purposes, you can consider them unique. How low? About 1 in 5.3×10^36 (that's a 1 followed by 36 zeros) - way more atoms than exist on Earth!

[2]:
// Import the uuid package
import { v4 as uuidv4 } from 'uuid';

// Generate a simple UUID using v4 (random)
const myUUID = uuidv4();
console.log(`Just generated a shiny new UUID: ${myUUID}\n`);
Just generated a shiny new UUID: 3d98e665-05e6-43e1-843a-7efadcdb8c3a
[M]:

UUID Versions - Which One Should You Use?

There are multiple UUID versions, each with different generation mechanisms and use cases. The most common ones are v1, v4, and v5.

[M]:

Version 4: Random UUIDs

Version 4 UUIDs are generated using random numbers. These are the most common type and are perfect when you need something unpredictable with no embedded information.

[3]:
// Generate a v4 UUID (random)
const randomId = uuidv4();
console.log(`UUID v4 (random): ${randomId}\n`);

// Generate a bunch of them
console.log(`Random UUID #1: ${uuidv4()}\n`);
console.log(`Random UUID #2: ${uuidv4()}\n`);
console.log(`Random UUID #3: ${uuidv4()}\n`);

// Notice how v4 UUIDs aren't sequential or predictable at all
UUID v4 (random): b443e34d-4fa4-4a1c-9708-7d8513a4aa70
Random UUID #1: f03fb726-c21c-4d7d-b708-34ec53546288
Random UUID #2: 8000398c-a188-43d7-837c-b0004b581f8c
Random UUID #3: 27705e8f-6b47-438b-ace1-e94a105b23ce
[M]:

Version 1: Time-Based UUIDs

UUID v1 combines the current timestamp with the MAC address of the computer. This makes them sortable by creation time, which can be handy for certain database operations.

[4]:
// Import v1 function
import { v1 as uuidv1 } from 'uuid';

// Generate a v1 UUID (time-based)
const timeBasedId = uuidv1();
console.log(`UUID v1 (time-based): ${timeBasedId}\n`);

// Generate a few more and notice the pattern
console.log(`Another v1 UUID: ${uuidv1()}\n`);
console.log(`And another v1 UUID: ${uuidv1()}\n`);

// Notice how these are sequential and can be sorted by generation time
UUID v1 (time-based): 19b7c8e0-00de-11f0-8323-87dc846d27c0
Another v1 UUID: 19b7eff0-00de-11f0-8323-87dc846d27c0
And another v1 UUID: 19b7eff1-00de-11f0-8323-87dc846d27c0
[M]:

Version 5: Name-Based UUIDs (SHA-1)

Version 5 UUIDs are generated from a namespace and a name. Given the same inputs, they'll always generate the same UUID - perfect for creating IDs from existing data.

[5]:
// Import v5 function
import { v5 as uuidv5 } from 'uuid';

// Generate v5 UUIDs (name-based with SHA-1 hash)
// The UUID namespace for URLs (a predefined namespace)
const URL_NAMESPACE = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';

// Create UUIDs from names in that namespace
const urlId1 = uuidv5('https://example.com', URL_NAMESPACE);
console.log(`UUID v5 for https://example.com: ${urlId1}\n`);

const urlId2 = uuidv5('https://another-example.com', URL_NAMESPACE);
console.log(`UUID v5 for https://another-example.com: ${urlId2}\n`);

// Regenerate the same UUID - notice it's identical to the first one
const sameAsUrlId1 = uuidv5('https://example.com', URL_NAMESPACE);
console.log(`Regenerated UUID for https://example.com: ${sameAsUrlId1}\n`);
console.log(`Are they the same? ${urlId1 === sameAsUrlId1}\n`);
UUID v5 for https://example.com: 4fd35a71-71ef-5a55-a9d9-aa75c889a6d0
UUID v5 for https://another-example.com: 2ce95335-6940-5fdb-a369-07ee5a25bbe2
Regenerated UUID for https://example.com: 4fd35a71-71ef-5a55-a9d9-aa75c889a6d0
Are they the same? true
[M]:

Validating UUIDs

The uuid package provides functionality to check if a string is a valid UUID and to determine which version it is.

[6]:
// Import validation functions
import { validate, version } from 'uuid';

// Test some strings
const validUuid = uuidv4();
const invalidUuid = 'definitely-not-a-uuid';

console.log(`Is "${validUuid}" a valid UUID? ${validate(validUuid)}\n`);
console.log(`Is "${invalidUuid}" a valid UUID? ${validate(invalidUuid)}\n`);

// Check the version of a UUID
console.log(`The version of ${validUuid} is: ${version(validUuid)}\n`);

// Create a validator for a specific version
function isUuidv4(uuid) {
return validate(uuid) && version(uuid) === 4;
}

console.log(`Is our UUID a valid v4? ${isUuidv4(validUuid)}\n`);
Is "7bb63bfb-e73b-4a2b-b476-c321bccf029e" a valid UUID? true
Is "definitely-not-a-uuid" a valid UUID? false
The version of 7bb63bfb-e73b-4a2b-b476-c321bccf029e is: 4
Is our UUID a valid v4? true
[M]:

Special UUIDs

The uuid package includes some special predefined UUIDs.

[7]:
// Import NIL value
import { NIL } from 'uuid';

// The NIL UUID is all zeros
console.log(`NIL UUID (all zeros): ${NIL}\n`);

// Checking if a UUID is the NIL UUID
const emptyId = NIL;
console.log(`Is it the NIL UUID? ${emptyId === NIL}\n`);
NIL UUID (all zeros): 00000000-0000-0000-0000-000000000000
Is it the NIL UUID? true
[M]:

Real-World Example: User Management System

Let's build a simple user management system using UUIDs for different purposes:

[8]:
import { v4 as uuidv4, v1 as uuidv1, v5 as uuidv5 } from 'uuid';

// Create a simple user management system
class UserSystem {
constructor() {
// Create a namespace for this specific app instance
this.namespace = uuidv4();
this.users = [];
this.sessions = [];
}
// Create a user with a random ID
createUser(email, name) {
const user = {
id: uuidv4(), // Random ID for the user
email,
name,
createdAt: new Date()
};
this.users.push(user);
return user;
}
// Create a user session with time-based ID
createSession(userId) {
const session = {
id: uuidv1(), // Time-based ID that can be sorted
userId,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000) // 1 hour from now
};
this.sessions.push(session);
return session;
}
Created user: {
  "id": "49ff1bd3-c83e-4740-989f-f43c24606676",
  "email": "alice@example.com",
  "name": "Alice",
  "createdAt": "2025-03-14T14:10:39.066Z"
}
Created session: {
  "id": "1b6292b0-00de-11f0-8323-87dc846d27c0",
  "userId": "49ff1bd3-c83e-4740-989f-f43c24606676",
  "createdAt": "2025-03-14T14:10:39.067Z",
  "expiresAt": "2025-03-14T15:10:39.067Z"
}
Verification token for alice@example.com: c65f4bbf-6d5a-5455-93ef-debfb4e07c98
Generated again: c65f4bbf-6d5a-5455-93ef-debfb4e07c98
Same token? true
[M]:

Using UUIDs as Database Keys

Here's a quick comparison of UUIDs vs. auto-increment IDs for databases:

[9]:
// Mock database to compare ID strategies
class MockDatabase {
constructor() {
this.autoIncrementCounter = 0;
this.autoIncrementRecords = {};
this.uuidRecords = {};
}
// Insert with auto-increment ID
insertWithAutoId(data) {
this.autoIncrementCounter += 1;
const id = this.autoIncrementCounter;
this.autoIncrementRecords[id] = { id, ...data };
return id;
}
// Insert with UUID
insertWithUuid(data) {
const id = uuidv4();
this.uuidRecords[id] = { id, ...data };
return id;
}
// Simulate distributed inserts (like from multiple servers)
simulateDistributedInserts(count) {
console.log(`Simulating ${count} distributed inserts...\n`);
// This would fail with auto-increment IDs across different servers
// but works with UUIDs
const ids = [];
for (let i = 0; i < count; i++) {
ids.push(this.insertWithUuid({ name: `Record ${i}` }));
}
// Check for uniqueness (collisions would be a problem)
const uniqueIds = new Set(ids);
Simulating 5 distributed inserts...
Generated 5 IDs
Unique IDs: 5
Collisions: 0
Sample UUID: 900ff63b-2a05-4fb5-a02d-b4802c9ae228
[M]:

Performance and Storage Considerations

Let's look at the performance and storage implications of UUIDs:

[10]:
// Performance test for generating UUIDs
function performanceTest() {
const iterations = 10000;
console.log(`Generating ${iterations} random UUIDs...\n`);
// Time generating v4 UUIDs
console.time('uuidv4-generation');
for (let i = 0; i < iterations; i++) {
uuidv4();
}
console.timeEnd('uuidv4-generation');
console.log('\n');
// Compare storage requirements
const intId = 12345;
const uuidStr = uuidv4();
console.log(`Integer ID: ${intId} (${intId.toString().length} chars)\n`);
console.log(`UUID: ${uuidStr} (${uuidStr.length} chars)\n`);
// Memory usage in JavaScript
console.log(`Approximate memory for 1 million integer IDs: ${(4 * 1000000) / (1024 * 1024)} MB\n`);
console.log(`Approximate memory for 1 million UUID strings: ${(36 * 1000000) / (1024 * 1024)} MB\n`);
}

performanceTest();
Error during execution: console.time is not a functionGenerating 10000 random UUIDs...
[M]:

When to Use UUIDs vs Other ID Systems

UUIDs aren't always the right choice. Here are some guidelines on when to use them:

Use UUIDs when:

  • You need distributed ID generation without central coordination
  • You want to generate IDs client-side before sending to the server
  • You need to hide sequential patterns for security or privacy
  • You're building systems that will scale across multiple databases/services
  • You need to merge datasets without ID conflicts

Consider alternatives when:

  • Storage space is critically limited (UUIDs use 16 bytes vs 4-8 for integers)
  • You need absolutely optimal database indexing performance
  • You need IDs that are easy for humans to type or remember
  • Your use case requires strictly sequential numbers (invoice numbers, etc.)

UUIDs might seem like overkill for small projects, but they give you tremendous flexibility as your application grows! Think of them as future-proofing your ID system!

Sign in to save your work and access it from anywhere