UUID and Nano ID Generator
Generate RFC-4122 v4 UUIDs and URL-safe nano IDs using the Node.js built-in crypto module with zero deps.
import crypto from 'crypto';
export function uuid(): string {
return crypto.randomUUID();
}
export function nanoId(size = 21): string {
const alphabet =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
const bytes = crypto.randomBytes(size);
let id = '';
for (let i = 0; i < size; i++) {
id += alphabet[bytes[i] & 63];
}
return id;
}
export function prefixedId(prefix: string, size = 12): string {
return `${prefix}_${nanoId(size)}`;
}
// Usage:
// uuid() -> 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
// nanoId() -> 'V1StGXR8_Z5jdHi6B-myT'
// prefixedId('usr') -> 'usr_a1B2c3D4e5F6'Use Cases
- Database primary keys
- Session identifiers
- URL-safe short IDs
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
useCopyToClipboard Hook
Copy text to clipboard with success state and automatic reset timer using the Clipboard API.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.