Overview
Zod provides functions for validating CUIDs (Collision-resistant Unique IDentifiers):z.cuid()- Validates CUID (original format)z.cuid2()- Validates CUID2 (improved format)
~/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:- Start with
corC - Be at least 9 characters long (1 prefix + 8+ characters)
- Contain no spaces or hyphens after the prefix
- 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:- Can be as short as 1 character
- Typically 24-32 characters long (default)
- Can be longer depending on configuration
- 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)
- Older algorithm
- Less flexible
- Potentially slower
CUID2 (Improved)
Pros:- Better performance
- Improved security
- Configurable length
- More entropy
- Smaller default size (24 chars)
- Newer format (less ecosystem support)
- Variable length
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)
Related Methods
- z.uuid() - UUID validation
- z.nanoid() - NanoID validation
- z.ulid() - ULID validation