NewSortable IDs are here
prefID
Menu

Zod (prefID-zod)

Validate prefixed IDs inside the schemas you already write. prefID-zod turns prefID's isId guard into a Zod schema for request bodies, forms, and config.

prefID-zod is a tiny companion package that bridges prefID and Zod. prefID's isId() is a type guard; prefID-zod exposes the same check as a Zod schema, so a prefixed ID drops straight into the validation you run at the edge of your app.

Install

prefid ships as a dependency and zod is a peer dependency, so your app's version of Zod is the one that runs. prefID itself stays dependency-free.

bash
npm install prefid-zod prefid zod

Usage

Use zId(prefix) anywhere you'd use a Zod schema. Invalid IDs are rejected before they reach your database, and the parsed value keeps prefID's literal type.

import { z } from "zod";
import { zId } from "prefid-zod";

const CreateOrder = z.object({
  userId: zId("user"), // validated AND typed `user_${string}`
  amount: z.number().positive(),
});

CreateOrder.parse({ userId: "user_a8Kd0f2b", amount: 42 }); // ✅
CreateOrder.parse({ userId: "order_9f8e7d", amount: 42 }); // ❌ throws — wrong prefix
const { z } = require("zod");
const { zId } = require("prefid-zod");

const CreateOrder = z.object({
  userId: zId("user"), // must be a "user_…" id
  amount: z.number().positive(),
});

CreateOrder.parse({ userId: "user_a8Kd0f2b", amount: 42 }); // ✅
CreateOrder.parse({ userId: "order_9f8e7d", amount: 42 }); // ❌ throws — wrong prefix

What you get

  • Runtime validation — a value with the wrong prefix (or that isn't a string at all) fails parse, using prefID's own isId under the hood.
  • Type narrowing — the parsed field is typed `${prefix}_${string}`, not plain string, so the compiler still stops you from passing a user ID where an order ID is expected.
  • Composable — it's an ordinary Zod schema, so it nests inside z.object, z.array, and works with safeParse.

Options

ts
zId("user", { separator: "-" });        // matches "user-…" instead of "user_…"
zId("user", { message: "Invalid user id" }); // custom error message
  • separator — match a non-default separator (mirrors createId's separator). Default "_".
  • message — a custom error message for the failure.

Links