❯ehsan.blog
~/blog/your-standard-schema-check-passes-then-crashes — zsh
❯cat your-standard-schema-check-passes-then-crashes.md

Your Standard Schema check passes, then crashes on the next line

·6 min read

Your Standard Schema check passes, then crashes on the next line — article card for a post by Ehsan Shahid

If you write a library that accepts “any schema the caller already uses”, you have probably written this check:

js
if ('~standard' in schema) {
  // great, it's a Standard Schema, I can work with this
}

That check used to be safe. It isn’t anymore.

Standard Schema started as one interface. It is now a family of them, and every member marks itself with the same ~standard key. So the key tells you a schema belongs to the family. It no longer tells you what that schema can do.

Below is a crash you can run in about two minutes, using Zod and Valibot as they ship today.

First, the thing that changed

Standard Schema is a tiny agreement between validation libraries. A library puts one property on its schema objects, called ~standard, and anybody can read it. No shared dependency, no adapters. I leaned on exactly this when I built schema validation into my logger, so the package could accept a Zod schema or a Valibot one without depending on either.

In version 1.0.0 of the spec there was exactly one interface, StandardSchemaV1, and it looked roughly like this:

ts
interface Props {
  readonly version: 1
  readonly vendor: string
  readonly validate: (value: unknown) => Result | Promise<Result>
  readonly types?: Types
}

One interface, one key, one capability. If ~standard was there, validate was there.

In 1.1.0 the spec was split into three pieces:

  • StandardTypedV1 is the new base. It carries only version, vendor, and an optional types. It cannot validate anything.
  • StandardSchemaV1 extends the base and adds validate.
  • StandardJSONSchemaV1 extends the base and adds jsonSchema, which turns the schema into a real JSON Schema document.

Here is the part that bites. All three put their properties under the same ~standard key. A library can implement one of them, two of them, or all three. Nothing in the key itself says which.

So '~standard' in schema now answers a much weaker question than you think it does. It answers “is this from the family?” when you wanted “can this do the job I’m about to ask of it?”

Reproduce the crash

Make a folder and install two real libraries:

bash
npm init -y
npm i zod@4.6.7 valibot@1.5.0

Save this as demo.mjs:

js
import * as z from 'zod'
import * as v from 'valibot'

const zodSchema = z.object({ email: z.string() })
const valibotSchema = v.object({ email: v.string() })

// The old check. "Does it have the marker key?"
const looksStandard = (s) => typeof s === 'object' && s !== null && '~standard' in s

console.log('zod     looksStandard:', looksStandard(zodSchema))
console.log('valibot looksStandard:', looksStandard(valibotSchema))

// Both true. Now ask each one for a JSON Schema.
for (const [name, schema] of [['zod', zodSchema], ['valibot', valibotSchema]]) {
  try {
    const json = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' })
    console.log(name, 'json schema ->', JSON.stringify(json))
  } catch (err) {
    console.log(name, 'CRASHED ->', err.constructor.name + ':', err.message)
  }
}

Run it with node demo.mjs. This is the real output:

plaintext
zod     looksStandard: true
valibot looksStandard: true
zod json schema -> {"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"email":{"type":"string"}},"required":["email"]}
valibot CRASHED -> TypeError: Cannot read properties of undefined (reading 'input')

Two schemas. Both pass the check. One works, one throws.

Nothing here is broken or buggy, by the way. Both libraries are doing exactly what the spec allows. Zod implements the JSON Schema interface. Valibot, at 1.5.0, implements the validation interface and not that one. Your check was the wrong check.

What each library actually puts in there

You don’t have to take my word for it. Print the keys:

js
import * as z from 'zod'
import * as v from 'valibot'

console.log('zod    ', Object.keys(z.object({ a: z.string() })['~standard']))
console.log('valibot', Object.keys(v.object({ a: v.string() })['~standard']))
plaintext
zod     [ 'validate', 'vendor', 'version', 'jsonSchema' ]
valibot [ 'version', 'vendor', 'validate' ]

Zod 4.6.7 gives you both capabilities. Valibot 1.5.0 gives you one. Same key, different contents.

This gap is going to get wider, not narrower, because that is the point of splitting the spec. A library that only describes types, and never validates at runtime, can now join the family by implementing the base interface alone. When that library shows up, '~standard' in schema will be true and validate will be undefined — the same crash, pointing at the other property.

The fix: ask for the capability, not the key

Stop checking whether the marker exists. Check whether the function you are about to call exists.

js
const props = (s) => (typeof s === 'object' && s !== null ? s['~standard'] : undefined)

const canValidate = (s) => typeof props(s)?.validate === 'function'
const canJsonSchema = (s) => typeof props(s)?.jsonSchema?.input === 'function'

Two small helpers, and the crash is gone:

js
for (const schema of [zodSchema, valibotSchema]) {
  const vendor = props(schema).vendor
  if (canJsonSchema(schema)) {
    console.log(vendor, 'json ok')
  } else {
    console.log(vendor, 'skipped, no jsonSchema')
  }
}
plaintext
zod json ok
valibot skipped, no jsonSchema

Three details in those helpers earn their place:

  • The typeof s === 'object' && s !== null guard. '~standard' in s throws if s is null, a number, or a string, so a bare in check is not safe on untrusted input anyway.
  • typeof ... === 'function', not a truthy check. A schema could carry a validate property that is not callable. You find out when you call it, which is the worst time.
  • ?.jsonSchema?.input. jsonSchema is an object holding input and output converters, so the thing you actually need is one level deeper.

And when a schema lacks the capability, skip it or throw your own clear error. A message like “this schema does not support JSON Schema output” is a thing a user can act on. Cannot read properties of undefined is not.

Two more surprises I hit while testing this

types does not exist at runtime. The spec declares types as an optional property, and InferInput and InferOutput read from it. It is purely a TypeScript carrier. Print it and you get nothing:

js
console.log(z.object({ a: z.string() })['~standard'].types)   // undefined
console.log(v.object({ a: v.string() })['~standard'].types)   // undefined

Both libraries, both undefined. Use it in types all you like. Never read it at runtime.

An unknown JSON Schema target may not throw. The spec says a library should throw if it does not support the target you ask for. “Should”, not “must”. Zod 4.6.7 currently does not:

js
z.string()['~standard'].jsonSchema.input({ target: 'nonsense-draft' })
// -> { type: 'string' }

No error. You get a document back, just without the $schema line a real target produces. If your code branches on the target version, validate that string yourself before you pass it in. Don’t assume a bad value will be rejected for you.

The one-line version

~standard is a family badge, not a capability list. Checking for the badge tells you a schema showed up. It does not promise the schema can do the specific thing on your next line.

Check for the function you are about to call. It is two lines, it costs nothing, and it keeps working as the family grows.

Versions used throughout: @standard-schema/spec 1.1.0, zod 4.6.7, valibot 1.5.0, Node 22. Library capabilities change — the whole point of this post is to check at runtime rather than trust a table in a blog post, including this one.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.