typescriptbeginner

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.

typescript
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.