Overview
Thez.nanoid() function validates NanoIDs - compact, URL-safe unique identifiers designed as a smaller, faster alternative to UUIDs.
~/workspace/source/packages/zod/src/v4/classic/schemas.ts:549
Basic Usage
Validation Rules
A valid NanoID must:- Be exactly 21 characters long
- Contain only:
a-z,A-Z,0-9,_(underscore),-(hyphen) - Match pattern:
/^[a-zA-Z0-9_-]{21}$/
Valid Examples
Invalid Examples
Custom Error Message
Error Details
When validation fails, the error includes the expected pattern:Parameters
string: Custom error messageNanoIDParams: Object with:message?: string: Custom error message
Examples
Database Primary Key
API Request Tracking
URL-Safe Identifiers
Form Validation
Optional NanoID
Return Type
Returns aZodNanoID schema that validates and returns strings.
NanoID Characteristics
Advantages
- Compact: Only 21 characters (vs 36 for UUIDs)
- URL-safe: No special encoding needed
- Fast: Simple generation algorithm
- Collision-resistant: 2^126 unique IDs (vs 2^122 for UUID v4)
- Readable: Uses a larger alphabet than hex
Limitations
- Fixed length: Always 21 characters (not configurable in validator)
- Not sortable: Random generation, no time component
- Case-sensitive: Must preserve exact casing
NanoIDs are designed to be URL-safe and don’t require special encoding when used in URLs, making them ideal for public-facing identifiers like short links, share URLs, and API endpoints.
Use Cases
When to Use NanoID
- Short URLs and slugs
- Public-facing IDs
- Session identifiers
- API keys (combined with other security measures)
- Database primary keys (when size matters)
- Client-generated IDs
- Mobile applications (smaller payload)
When NOT to Use NanoID
- When you need sortable IDs (use UUID v7 or ULID)
- When you need specific length requirements
- When case-insensitivity is required
- Legacy systems expecting UUIDs
Comparison with Other IDs
Related Methods
- z.uuid() - UUID validation
- z.cuid() - CUID validation
- z.string().regex() - Custom pattern validation