Appearance
Generate UUID in TypeScript
TypeScript UUID generation works the same as JavaScript but with added type safety. The simplest way is using the built-in crypto.randomUUID()
function:
typescript
// Generate UUID version 4 with type safety
const uuid: string = crypto.randomUUID();
console.log(`Generated UUID: ${uuid}`);
// With proper typing for UUID format
type UUID = `${string}-${string}-${string}-${string}-${string}`;
const typedUuid: UUID = crypto.randomUUID() as UUID;
console.log(`Typed UUID: ${typedUuid}`);
For generating specific UUID versions with full type support, use the uuid library with TypeScript types:
typescript
import { v1, v3, v4, v5, v6, v7 } from 'uuid';
// Type-safe UUID generation
const uuid1: string = v1();
const uuid3: string = v3('name', v4());
const uuid4: string = v4();
const uuid5: string = v5('name', v4());
const uuid6: string = v6();
const uuid7: string = v7();
console.log('UUID v1:', uuid1);
console.log('UUID v3:', uuid3);
console.log('UUID v4:', uuid4);
console.log('UUID v5:', uuid5);
console.log('UUID v6:', uuid6);
console.log('UUID v7:', uuid7);
Installation & Setup
NPM Installation:
bash
npm install uuid
npm install --save-dev @types/uuid
Yarn Installation:
bash
yarn add uuid
yarn add --dev @types/uuid
Advanced TypeScript Usage
Custom UUID Types and Interfaces:
typescript
import { v4 } from 'uuid';
// Define UUID type
type UUID = string;
// Interface with UUID
interface User {
id: UUID;
name: string;
email: string;
createdAt: Date;
}
// Factory function with proper typing
function createUser(name: string, email: string): User {
return {
id: v4(),
name,
email,
createdAt: new Date(),
};
}
// Usage
const user: User = createUser('John Doe', '[email protected]');
console.log(user);
Generic UUID Service Class:
typescript
import { v1, v3, v4, v5, v6, v7 } from 'uuid';
type UUIDVersion = 1 | 3 | 4 | 5 | 6 | 7;
class UUIDService {
static generate(version: UUIDVersion = 4, name?: string, namespace?: string): string {
switch (version) {
case 1:
return v1();
case 3:
if (!name || !namespace) throw new Error('Name and namespace required for v3');
return v3(name, namespace);
case 4:
return v4();
case 5:
if (!name || !namespace) throw new Error('Name and namespace required for v5');
return v5(name, namespace);
case 6:
return v6();
case 7:
return v7();
default:
throw new Error(`Unsupported UUID version: ${version}`);
}
}
static validate(uuid: string): boolean {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
}
}
// Usage with type safety
const uuid: string = UUIDService.generate(4);
const isValid: boolean = UUIDService.validate(uuid);
React/Next.js Integration
React Hook for UUID Generation:
typescript
import { useState, useCallback } from 'react';
import { v4 } from 'uuid';
interface UseUUIDReturn {
uuid: string;
regenerate: () => void;
}
export const useUUID = (): UseUUIDReturn => {
const [uuid, setUuid] = useState<string>(() => v4());
const regenerate = useCallback(() => {
setUuid(v4());
}, []);
return { uuid, regenerate };
};
// Component usage
const MyComponent: React.FC = () => {
const { uuid, regenerate } = useUUID();
return (
<div>
<p>UUID: {uuid}</p>
<button onClick={regenerate}>Generate New</button>
</div>
);
};
Next.js API Route:
typescript
// pages/api/uuid.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { v4 } from 'uuid';
interface UUIDResponse {
uuid: string;
timestamp: string;
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<UUIDResponse>
) {
if (req.method === 'GET') {
res.status(200).json({
uuid: v4(),
timestamp: new Date().toISOString(),
});
} else {
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Node.js & Express Integration
Express Middleware:
typescript
import express, { Request, Response, NextFunction } from 'express';
import { v4 } from 'uuid';
// Extend Request interface
declare global {
namespace Express {
interface Request {
requestId: string;
}
}
}
// Middleware to add request ID
const addRequestId = (req: Request, res: Response, next: NextFunction): void => {
req.requestId = v4();
res.setHeader('X-Request-ID', req.requestId);
next();
};
const app = express();
app.use(addRequestId);
app.get('/api/data', (req: Request, res: Response) => {
res.json({
requestId: req.requestId,
data: 'Your data here',
});
});
UUID Version Comparison
Choose the right version for your TypeScript application:
- Version 1 - Time-based, includes MAC address
- Version 3 - MD5 namespace-based, deterministic
- Version 4 - Random, most popular choice
- Version 5 - SHA-1 namespace-based, more secure than v3
- Version 6 - Time-ordered, better than v1 for databases
- Version 7 - Modern time-based with improved sorting
For TypeScript applications:
- React/Vue apps: Use Version 4 for component keys and state management
- Node.js APIs: Consider Version 7 for request tracing and logging
- Database models: Use Version 6 for time-ordered entities
How do I generate UUID in other languages?
JavaScript ecosystem:
- JavaScript - crypto.randomUUID() & uuid library
Backend development:
- Java - Enterprise applications
- Python - Built-in uuid module
- C# - System.Guid & UuidCreator
- Go - google/uuid package
Modern development:
- Rust - uuid crate