Validate h3 and Nuxt requests with zod.
Important
Starting with h3 version 1.8.0, built-in runtime + type-safe request utilities are included, so you might not need this module.
npm install zod h3-zod
Import it like:
import { zh } from 'h3-zod';
// Or
import { useSafeValidatedQuery, useSafeValidatedBody } from 'h3-zod';
Helpers that don't throw when parsing fails:
export default defineEventHandler(async (event) => {
const query = await zh.useSafeValidatedQuery(event, z.object({
required: z.string()
}))
const body = await zh.useSafeValidatedBody(event, z.object({
optional: z.string().optional(),
required: z.boolean()
}))
const params = await zh.useSafeValidatedParams(event, {
id: z.number()
})
if (!params.success) {
// params.error
}
})
Helpers that throw error 400 when parsing fails:
export default defineEventHandler(async (event) => {
const query = await zh.useValidatedQuery(event, z.object({
required: z.string()
}))
const body = await zh.useValidatedBody(event, z.object({
optional: z.string().optional(),
required: z.boolean()
}))
const params = await zh.useValidatedParams(event, {
id: z.number()
})
})
You can also pass an object schema:
export default defineEventHandler(async (event) => {
const body = await zh.useValidatedBody(event, {
optional: z.string().optional(),
required: z.boolean()
})
})
"true"
→true
"false"
→false
"notboolean"
→ throwsZodError
"on"
→true
undefined
→false
"anythingbuton"
→ throwsZodError
"3"
→3
"3.14"
→ throwsZodError
"notanumber"
→ throwsZodError
"3"
→3
"3.14"
→3.14
"notanumber"
→ throwsZodError
const Schema = z.object({
isAdmin: zh.boolAsString,
agreedToTerms: zh.checkboxAsString,
age: zh.intAsString,
cost: zh.numAsString,
});
const parsed = Schema.parse({
isAdmin: 'true',
agreedToTerms: 'on',
age: '38',
cost: '10.99'
});
console.log(parsed)
// {
// isAdmin: true,
// agreedToTerms: true,
// age: 38,
// cost: 10.99
// }
MIT