| name | uuid |
| description | UUID generation skill - Universally Unique Identifiers v4 and v7 for entity IDs. For ng-events construction site progress tracking system. |
UUID - Universally Unique Identifiers
Trigger patterns: "UUID", "unique ID", "identifier", "v4", "v7", "uuidv4", "uuidv7"
Overview
UUID library for generating RFC9562-compliant unique identifiers in JavaScript/TypeScript applications.
Package: uuid@13.0.0
Standard: RFC9562 (formerly RFC4122)
Core Functions
1. v4() - Random UUID (Most Common)
Generates a version 4 UUID using cryptographically secure random values.
import { v4 as uuidv4 } from 'uuid';
const taskId = uuidv4();
interface Task {
id: string;
title: string;
createdAt: Date;
}
function createTask(title: string): Task {
return {
id: uuidv4(),
title,
createdAt: new Date()
};
}
When to use:
- Entity IDs (tasks, users, blueprints)
- Session IDs
- Request tracking IDs
- File upload IDs
- Any unique identifier needs
2. v7() - Timestamp-based UUID (Sortable)
Generates a version 7 UUID with Unix epoch timestamp for natural chronological sorting.
import { v7 as uuidv7 } from 'uuid';
const orderId = uuidv7();
const ids = Array.from({ length: 5 }, () => uuidv7());
interface Order {
id: string;
customerId: string;
createdAt: Date;
}
When to use:
- Database primary keys requiring chronological sorting
- Event IDs in time-series data
- Log entry IDs
- Audit trail records
- Any scenario where temporal ordering matters
Advantages:
- Natural sort order by creation time
- Better database index performance
- Reduced fragmentation in B-tree indexes
- Compatible with UUID v4 in storage/APIs
Real-World Examples
Task Repository with UUID
import { Injectable, inject } from '@angular/core';
import { Firestore, collection, doc, setDoc, getDoc } from '@angular/fire/firestore';
import { v4 as uuidv4 } from 'uuid';
export interface Task {
id: string;
blueprintId: string;
title: string;
description: string;
status: 'pending' | 'in-progress' | 'completed';
createdAt: Date;
updatedAt: Date;
}
@Injectable({ providedIn: 'root' })
export class TaskRepository {
private firestore = inject(Firestore);
private tasksCollection = collection(this.firestore, 'tasks');
async create(task: Omit<Task, 'id' | | >): <> {
id = ();
now = ();
: = {
...task,
id,
: now,
: now
};
docRef = (., id);
(docRef, newTask);
newTask;
}
(: ): < | > {
docRef = (., id);
snapshot = (docRef);
(!snapshot.()) {
;
}
{ : snapshot., ...snapshot.() } ;
}
}
Audit Log with UUID v7
import { Injectable, inject } from '@angular/core';
import { Firestore, collection, doc, setDoc } from '@angular/fire/firestore';
import { v7 as uuidv7 } from 'uuid';
export interface AuditLog {
id: string;
userId: string;
action: string;
resource: string;
resourceId: string;
timestamp: Date;
metadata?: Record<string, any>;
}
@Injectable({ providedIn: 'root' })
export class AuditLogRepository {
private firestore = inject(Firestore);
private logsCollection = collection(this.firestore, 'auditLogs');
async log(
userId: string,
: ,
: ,
: ,
?: <, >
): <> {
id = ();
: = {
id,
userId,
action,
resource,
resourceId,
: (),
metadata
};
docRef = (., id);
(docRef, log);
log;
}
}
Session Management
import { Injectable } from '@angular/core';
import { v4 as uuidv4 } from 'uuid';
export interface Session {
id: string;
userId: string;
token: string;
createdAt: Date;
expiresAt: Date;
}
@Injectable({ providedIn: 'root' })
export class SessionService {
private sessions = new Map<string, Session>();
createSession(userId: string, expiresInMs: number = 3600000): Session {
const sessionId = uuidv4();
const now = new Date();
const session: Session = {
id: sessionId,
userId,
token: this.generateToken(),
: now,
: (now.() + expiresInMs)
};
..(sessionId, session);
session;
}
(: ): | {
..(sessionId) || ;
}
(): {
();
}
}
File Upload Tracking
import { Injectable, signal } from '@angular/core';
import { v4 as uuidv4 } from 'uuid';
export interface FileUpload {
id: string;
fileName: string;
fileSize: number;
uploadedBy: string;
uploadedAt: Date;
status: 'pending' | 'uploading' | 'completed' | 'failed';
progress: number;
url?: string;
}
@Injectable({ providedIn: 'root' })
export class FileUploadService {
private uploads = signal<Map<string, FileUpload>>(new Map());
startUpload(file: File, userId: string): string {
const uploadId = uuidv4();
const upload: = {
: uploadId,
: file.,
: file.,
: userId,
: (),
: ,
:
};
..( {
map.(uploadId, upload);
(map);
});
uploadId;
}
(: , : ): {
..( {
upload = map.(uploadId);
(upload) {
upload. = progress;
upload. = progress === ? : ;
map.(uploadId, upload);
}
(map);
});
}
(: ): | {
.().(uploadId);
}
}
Best Practices
1. v4 for General Use, v7 for Time-Series
✅ DO: Choose based on use case
const taskId = uuidv4();
const userId = uuidv4();
const logId = uuidv7();
const eventId = uuidv7();
2. Use TypeScript Types
✅ DO: Define UUID brand types for safety
type UUID = string & { readonly __brand: unique symbol };
interface Task {
id: UUID;
title: string;
}
function createTaskId(): UUID {
return uuidv4() as UUID;
}
3. Validate UUIDs
✅ DO: Validate UUID format
import { validate as uuidValidate, version as uuidVersion } from 'uuid';
function isValidUUID(id: string): boolean {
return uuidValidate(id);
}
function isV4UUID(id: string): boolean {
return uuidValidate(id) && uuidVersion(id) === 4;
}
function isV7UUID(id: string): boolean {
return uuidValidate(id) && uuidVersion(id) === 7;
}
4. Don't Store UUIDs as Binary (Firestore)
✅ DO: Store as string in Firestore
await setDoc(doc(collection, taskId), { });
❌ DON'T: Convert to binary in Firestore
const binaryId = Buffer.from(taskId.replace(/-/g, ''), 'hex');
Performance Considerations
- Generation Speed: v4 is slightly faster than v7
- Index Performance: v7 provides better database index locality
- Storage: Both require 36 bytes as string (128-bit + hyphens)
- Collision Probability: Effectively zero for both versions
CLI Usage
$ npx uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4
$ npx uuid v7
019a26ab-9a66-71a9-a89e-63c35fce4a5a
$ npx uuid && npx uuid && npx uuid
Integration Checklist
Anti-Patterns
❌ Using Sequential IDs in Distributed Systems:
let counter = 0;
const id = `task-${++counter}`;
✅ Use UUID:
const id = uuidv4();
❌ Parsing UUID Parts Manually:
const timestamp = parseInt(uuid.substring(0, 8), 16);
✅ Use Library Functions:
import { parse, version } from 'uuid';
const ver = version(uuid);
❌ Generating UUIDs Client-Side for Security-Critical Operations:
const sessionToken = uuidv4();
✅ Generate Security Tokens Server-Side:
const token = await auth.currentUser.getIdToken();
Cross-References
- firebase-repository - UUID for entity IDs
- blueprint-integration - Blueprint and member IDs
- event-bus-integration - Event ID generation
- angular-component - UUID in component state
Package Information
Version: 1.0
Created: 2025-12-25
Maintainer: ng-events(GigHub) Development Team