Zod Smart Coercion
A Plugin refined alternative to z.coerce that automatically converts inputs to the expected type without modifying the input schema.
WARNING
In Zod v4, this plugin only supports discriminated unions. Regular (non-discriminated) unions are not coerced automatically.
Installation
npm install @orpc/zod@latestyarn add @orpc/zod@latestpnpm add @orpc/zod@latestbun add @orpc/zod@latestdeno add npm:@orpc/zod@latestSetup
import { OpenAPIHandler } from '@orpc/openapi/fetch'
import { ZodSmartCoercionPlugin } from '@orpc/zod' // <-- zod v3
import {
experimental_ZodSmartCoercionPlugin as ZodSmartCoercionPlugin
} from '@orpc/zod/zod4' // <-- zod v4
const handler = new OpenAPIHandler(router, {
plugins: [new ZodSmartCoercionPlugin()]
})WARNING
Do not use this plugin with RPCHandler as it may negatively impact performance.
Safe and Predictable Conversion
Zod Smart Coercion converts data only when:
- The schema expects a specific type and the input can be converted.
- The input does not already match the schema.
For example:
- If the input is
'true'but the schema does not expect a boolean, no conversion occurs. - If the schema accepts both boolean and string,
'true'will not be coerced to a boolean.
Conversion Rules
Boolean
Converts string representations of boolean values:
const raw = 'true' // Input
const coerced = true // OutputSupported values:
'true','on','t'→true'false','off','f'→false
Number
Converts numeric strings:
const raw = '42' // Input
const coerced = 42 // OutputBigInt
Converts strings representing valid BigInt values:
const raw = '12345678901234567890' // Input
const coerced = 12345678901234567890n // OutputDate
Converts valid date strings into Date objects:
const raw = '2024-11-27T00:00:00.000Z' // Input
const coerced = new Date('2024-11-27T00:00:00.000Z') // OutputSupported formats:
- Full ISO date-time (e.g.,
2024-11-27T00:00:00.000Z) - Date only (e.g.,
2024-11-27)
RegExp
Converts strings representing regular expressions:
const raw = '/^abc$/i' // Input
const coerced = /^abc$/i // OutputURL
Converts valid URL strings into URL objects:
const raw = 'https://example.com' // Input
const coerced = new URL('https://example.com') // OutputSet
Converts arrays into Set objects, removing duplicates:
const raw = ['apple', 'banana', 'apple'] // Input
const coerced = new Set(['apple', 'banana']) // OutputMap
Converts arrays of key-value pairs into Map objects:
const raw = [
['key1', 'value1'],
['key2', 'value2']
] // Input
const coerced = new Map([
['key1', 'value1'],
['key2', 'value2']
]) // Output