Hono Validation
Zod Validator
ts
import { Hono } from 'hono'
import { z } from 'zod'
import { validator } from 'hono/validator'
const schema = z.object({
post: z.string(),
})
const app = new Hono()
app.post(
'/posts',
validator('json', (value, c) => {
const parsed = schema.safeParse(value)
if (!parsed.success) {
return c.json({ message: 'Invalid' }, 400)
}
return parsed.data
}),
(c) => {
const post = c.req.valid('json')
return c.json(
{
message: 'Created!',
post,
},
201,
)
},
)
export default app
REST Client
http
### Hono Zod Validator
POST http://localhost:3000/posts
Content-Type: application/json
{
"post": "Hono🔥"
}
HTTP/1.1 201 Created
Content-Type: application/json; charset=UTF-8
Date: ***, ** *** **** **:**:** ***
Content-Length: 49
{
"message": "Created!",
"post": {
"post": "Hono🔥"
}
}
Hono Zod Validator
ts
import { Hono } from 'hono'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
const schema = z.object({
post: z.string(),
})
const app = new Hono()
app.post('/posts', zValidator('json', schema), (c) => {
const post = c.req.valid('json')
return c.json(
{
message: 'Created!',
post,
},
201,
)
})
export default app
REST Client
http
### Hono Zod Validator
POST http://localhost:3000/posts
Content-Type: application/json
{
"post": "Hono🔥"
}
HTTP/1.1 201 Created
Content-Type: application/json; charset=UTF-8
Date: ***, ** *** **** **:**:** ***
Content-Length: 49
{
"message": "Created!",
"post": {
"post": "Hono🔥"
}
}