Generate UUID with Native crypto.randomUUID()
Modern browsers and Node.js 16+ support crypto.randomUUID() natively, requiring no external dependencies. This built-in method generates cryptographically secure random UUIDs (v4) with TypeScript's full type inference and compile-time checking.
Browser & Node.js Built-in
No dependencies needed for modern environments! TypeScript provides full type safety.
// Browser or Node.js 16+
const uuid: string = crypto.randomUUID();
console.log(uuid); // "550e8400-e29b-41d4-a716-446655440000"
✅ Browser Support
Chrome 92+, Firefox 95+, Safari 15.4+, Edge 92+
✅ Node.js Support
Node.js 16.7.0+ and 14.17.0+ (with flag)
Type-Safe UUID with Branded Types
Use TypeScript's branded types to create UUID-specific types that prevent mixing UUIDs with regular strings at compile time. This pattern provides zero-runtime overhead while catching UUID-related type errors during development.
// Branded UUID type
type UUID = string & { readonly brand: unique symbol };
// Type guard for runtime validation
function isUUID(value: string): value is UUID {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(value);
}
// Safe UUID creation
function createUUID(): UUID {
return crypto.randomUUID() as UUID;
}
// Parse UUID from string with validation
function parseUUID(value: string): UUID | null {
return isUUID(value) ? value : null;
}
// Usage
const userId: UUID = createUUID();
const orderId: UUID = createUUID();
// Type-safe - prevents mixing different IDs
function getUser(id: UUID) {
console.log(`Fetching user: ${id}`);
}
getUser(userId); // ✅ Works
// getUser("invalid"); // ❌ Type error!
Install uuid Package with Type Definitions
For UUID v1, v3, v5, and v7 support, install the uuid package with its TypeScript definitions. The @types/uuid package provides full type safety for all UUID generation methods and validation functions.
NPM Installation with Types
npm install uuid
npm install --save-dev @types/uuid
import { v1 as uuidv1, v4 as uuidv4, v5 as uuidv5, validate } from 'uuid';
// UUID v4 - Random
const id: string = uuidv4();
console.log(id); // "550e8400-e29b-41d4-a716-446655440000"
// UUID v1 - Timestamp-based
const timestampId: string = uuidv1();
// UUID v5 - Namespace-based (SHA-1)
const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const nameId: string = uuidv5('user@example.com', NAMESPACE);
// Validate UUID with type narrowing
function processUUID(value: string): void {
if (validate(value)) {
console.log(`Valid UUID: ${value}`);
} else {
console.error(`Invalid UUID: ${value}`);
}
}
TypeScript Interfaces with UUID Properties
Define strongly-typed interfaces with UUID fields for domain models, API responses, and database entities. TypeScript ensures all UUID fields are correctly typed throughout your application, catching type mismatches at compile time.
// User interface with UUID
interface User {
id: string; // UUID
email: string;
name: string;
createdAt: Date;
}
// Factory function with type safety
function createUser(email: string, name: string): User {
return {
id: crypto.randomUUID(),
email,
name,
createdAt: new Date()
};
}
// API response type
interface ApiResponse {
id: string; // Request UUID
data: T;
timestamp: number;
}
// Generic function with UUID
function wrapResponse(data: T): ApiResponse {
return {
id: crypto.randomUUID(),
data,
timestamp: Date.now()
};
}
// Usage
const user = createUser("alice@example.com", "Alice");
const response = wrapResponse(user);
console.log(response.id); // UUID of request
React Component Integration with TypeScript
Use UUIDs in React components with full TypeScript type safety. Generate unique keys for lists, track component state, and manage form inputs with compile-time guarantees that all UUID handling is correct.
import React, { useState } from 'react';
interface Todo {
id: string; // UUID
text: string;
completed: boolean;
}
const TodoList: React.FC = () => {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = (): void => {
if (!input.trim()) return;
const newTodo: Todo = {
id: crypto.randomUUID(),
text: input,
completed: false
};
setTodos([...todos, newTodo]);
setInput('');
};
const toggleTodo = (id: string): void => {
setTodos(todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
));
};
return (
setInput(e.target.value)}
placeholder="Add todo..."
/>
{todos.map((todo) => (
-
toggleTodo(todo.id)}
/>
{todo.text}
))}
);
};
export default TodoList;
Express.js with TypeScript UUID Middleware
Add request tracking middleware to Express applications with TypeScript type definitions. Each request gets a unique UUID for logging, debugging, and distributed tracing with full type safety across your middleware stack.
import express, { Request, Response, NextFunction } from 'express';
// Extend Express Request type
declare global {
namespace Express {
interface Request {
requestId?: string;
}
}
}
// UUID middleware
const requestIdMiddleware = (
req: Request,
res: Response,
next: NextFunction
): void => {
req.requestId = crypto.randomUUID();
res.setHeader('X-Request-ID', req.requestId);
next();
};
const app = express();
// Apply middleware
app.use(requestIdMiddleware);
// Route with request ID
app.get('/api/users/:id', (req: Request, res: Response) => {
console.log(`Request ID: ${req.requestId}`);
res.json({
requestId: req.requestId,
userId: req.params.id,
timestamp: new Date()
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});