Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Zod · Module

.nanoid

z.nanoid() creates a Zod schema for validating Nano ID strings. Use it wherever a schema is needed, including object fields and collections.

Since
Zod 4.5

How it works

z.nanoid() creates a string schema for Nano IDs. Parsing succeeds only for values that satisfy Nano ID validation; the schema can be composed with object schemas and used with standard Zod parsing methods.

Syntax

z.nanoid()

Returns

A Zod schema that validates Nano ID strings.

Key points

  • Nano ID validation appears among Zod's built-in string-format validators.
  • Use the Nano ID schema as the validation definition before parsing input.
  • A Nano ID schema can participate in larger composed schemas, including nested objects and arrays.

Example: Validate a Nano ID

import { z } from "zod";

const id = z.nanoid();

console.log(id.safeParse("V1StGXR8_Z5jdHi6B-myT").success); // true
console.log(id.safeParse("not-a-valid-nanoid").success); // false

Creates a Zod schema that accepts valid Nano ID strings and rejects values that do not match the Nano ID format.

When to use it

Input validation

Validate an identifier received from an API or form.

Structured records

Require Nano ID identifiers in a Zod object schema.

Collections

Validate multiple Nano IDs in one value.

Interview questions

QWhat does z.nanoid() do?

z.nanoid() defines a schema for validating Nano ID strings. It can be parsed directly or embedded in larger Zod schemas.

Follow-up: How would you validate an object identifier? Use z.object({ id: z.nanoid() }) and parse the input.

QWhy choose z.nanoid() instead of z.string()?

It is intended for Nano ID values rather than arbitrary strings. Invalid input is rejected through Zod's normal validation behavior.

Follow-up: How can rejection be handled without throwing? Call .safeParse() and inspect its success result.

QHow can z.nanoid() be combined with other schemas?

The schema is composable, so it can be used anywhere a Zod schema is accepted, including object properties and arrays.

Follow-up: How would you validate several IDs? Use z.array(z.nanoid()).

  • z.string()
  • z.uuid()
  • z.ulid()
  • z.cuid()
  • z.cuid2()
  • z.string().regex()

Source: Defining schemas | Zod. Checked 2026-10-15.