Skip to main content

Overview

The z.nanoid() function validates NanoIDs - compact, URL-safe unique identifiers designed as a smaller, faster alternative to UUIDs.
Location in source: ~/workspace/source/packages/zod/src/v4/classic/schemas.ts:549

Basic Usage

Validation Rules

A valid NanoID must:
  1. Be exactly 21 characters long
  2. Contain only: a-z, A-Z, 0-9, _ (underscore), - (hyphen)
  3. 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 message
  • NanoIDParams: Object with:
    • message?: string: Custom error message

Examples

Database Primary Key

API Request Tracking

URL-Safe Identifiers

Form Validation

Optional NanoID

Return Type

Returns a ZodNanoID 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
The validator checks for the standard 21-character NanoID format. If your application uses custom NanoID lengths or alphabets, you’ll need to create a custom validator using z.stringFormat() or z.string().regex().

Comparison with Other IDs