Skip to main content

Overview

Zod provides functions for validating CUIDs (Collision-resistant Unique IDentifiers):
  • z.cuid() - Validates CUID (original format)
  • z.cuid2() - Validates CUID2 (improved format)
Location in source: ~/workspace/source/packages/zod/src/v4/classic/schemas.ts:563-579

z.cuid()

Validates the original CUID format. CUIDs are designed to be collision-resistant, horizontally scalable, and offline-first.

Basic Usage

Validation Rules

A valid CUID must:
  1. Start with c or C
  2. Be at least 9 characters long (1 prefix + 8+ characters)
  3. Contain no spaces or hyphens after the prefix
  4. Match pattern: /^[cC][^\s-]{8,}$/

Valid Examples

Invalid Examples

Custom Error Message

Error Details

z.cuid2()

Validates CUID2 format, an improved version with better performance and security properties.

Basic Usage

Validation Rules

A valid CUID2:
  1. Can be as short as 1 character
  2. Typically 24-32 characters long (default)
  3. Can be longer depending on configuration
  4. Uses lowercase letters and numbers

Valid Examples

Custom Error Message

CUID2 is the recommended format for new projects. It offers improved performance, better security properties, and more flexible length configuration compared to the original CUID.

Parameters

Both functions accept an optional parameter:
  • string: Custom error message
  • Params object:
    • message?: string: Custom error message

Examples

Database Primary Keys

API Request IDs

Supporting Both Formats (Migration)

Form Validation with Custom Messages

Return Type

Both schemas return strings:

CUID vs CUID2

CUID (Original)

Pros:
  • Well-established format
  • Widely supported in libraries
  • Fixed length (~25 characters)
Cons:
  • Older algorithm
  • Less flexible
  • Potentially slower

CUID2 (Improved)

Pros:
  • Better performance
  • Improved security
  • Configurable length
  • More entropy
  • Smaller default size (24 chars)
Cons:
  • Newer format (less ecosystem support)
  • Variable length
While CUIDs are designed to be collision-resistant, they are not cryptographically secure. Do not use them for security tokens, passwords, or other security-sensitive purposes.

Use Cases

When to Use CUIDs

  • Database primary keys
  • Distributed system IDs
  • Client-generated IDs
  • Offline-first applications
  • Horizontal scaling scenarios
  • Request/transaction tracking

When NOT to Use CUIDs

  • Security tokens
  • Password reset tokens
  • API keys
  • Cryptographic operations
  • When you need sequential IDs
  • When you need lexicographically sortable IDs (use UUID v7 instead)