Validation and the RPC Client
17. How does validation work in Hono?
A validator is middleware for one target: json, form, query, param, header or cookie. It returns the validated value or a response, and the handler reads the typed result with c.req.valid(target).
The core validator() in hono/validator is a thin hook; the validation guide recommends a schema library on top.
import * as z from 'zod'
import { zValidator } from '@hono/zod-validator'
const CreatePost = z.object({ title: z.string().min(1).max(120), body: z.string() })
app.post(
'/posts/:id{[0-9]+}/comments',
zValidator('param', z.object({ id: z.coerce.number() })),
zValidator('json', CreatePost),
(c) => {
const { id } = c.req.valid('param')
const input = c.req.valid('json')
return c.json({ postId: id, ...input }, 201)
}
)
@hono/zod-validator (0.9.1 on npm) wraps Zod; @hono/standard-validator (0.4.1) exposes sValidator, which accepts any Standard Schema library such as Zod, Valibot or ArkType.
A strong candidate mentions that the validator also feeds the RPC client its input types, so validation is where the API contract lives.
18. Find the bug: these validator tests pass, but production rejects valid requests.
app.post(
'/orders',
validator('header', (v, c) => {
const key = v['Idempotency-Key']
if (!key) return c.json({ error: 'missing key' }, 400)
return { key }
}),
validator('json', (v) => v as Record<string, unknown>),
(c) => c.json({ received: c.req.valid('json') }, 201)
)
// test
const res = await app.request('/orders', {
method: 'POST',
body: JSON.stringify({ sku: 'A1' }),
})
expect(res.status).toBe(400)
The header validator reads 'Idempotency-Key', but Hono passes header names in lowercase, so v['Idempotency-Key'] is always undefined and every request gets a 400, including correct ones. The key must be 'idempotency-key'.
The test passes because it expects 400 for a different reason.
The JSON half has its own trap: a json or form validator only parses the body when the request has the matching Content-Type. The test sends none, so the validator receives {}.
Tests must set headers: { 'Content-Type': 'application/json' }, and a pass-through validator like this one should reject an empty object.
That last point is a real security issue: before 4.13.16, a multipart/form-data request with an extra parameter such as charset also reached the form validator as an empty object while the handler could still read every field.
19. How does the Hono RPC client work?
You export the type of your route chain from the server, and the client built by hc<AppType>(baseUrl) mirrors it: client.posts.$post({ json }), client.posts[':id'].$get({ param }).
Inputs come from validators and outputs from c.json() calls, with no code generation step and no OpenAPI file in between.
// server
const routes = new Hono()
.get('/posts/:id', async (c) => {
const post = await findPost(c.req.param('id'))
if (!post) return c.json({ error: 'not found' }, 404)
return c.json({ post }, 200)
})
export type AppType = typeof routes
// client
import { hc } from 'hono/client'
const client = hc<AppType>('https://api.example.com')
const res = await client.posts[':id'].$get({ param: { id: '42' } })
if (res.status === 404) {
const { error } = await res.json()
} else if (res.ok) {
const { post } = await res.json()
}
Passing the status to c.json() matters: the RPC guide shows that with explicit status codes the client can narrow the body type by res.status. Without them, the 404 and 200 bodies merge into one union and the client cannot tell them apart.
20. Find the bug: the client compiles, but every route is missing from its type.
const app = new Hono()
app.get('/posts', (c) => c.json(listPosts(), 200))
app.post('/posts', zValidator('json', NewPost), (c) => c.json(create(c.req.valid('json')), 201))
export type AppType = typeof app
export default app
typeof app is the type of new Hono() with no routes. Hono's route types accumulate in the return value of each .get() and .post() call, and statements on separate lines throw those return values away.
Chain the calls and export the type of the chain:
const app = new Hono()
.get('/posts', (c) => c.json(listPosts(), 200))
.post('/posts', zValidator('json', NewPost), (c) => c.json(create(c.req.valid('json')), 201))
export type AppType = typeof app
The same rule applies to testClient() in hono/testing and to app.route(): the type to export is the result of the chained route() calls, not the original instance. A candidate who has used RPC in a real project will have hit this.
21. The IDE slows down as the RPC app grows. What do you do?
Each route adds type instantiations that tsserver recomputes, and a large app can make autocompletion take seconds or fail with "Type instantiation is excessively deep". The RPC guide lists the fixes:
- Match Hono versions on server and client packages in a monorepo; a mismatch is a common cause of the deep-instantiation error.
- Set
"strict": true in both tsconfig files, which the RPC types require.
- Compile the client type ahead of time: export
hcWithType from the server package so tsc computes the client type once and the editor reads a declaration file.
- Split the client per sub-app instead of one client for the whole API.
- Use TypeScript project references when the frontend imports
AppType from another package.
// in the server package, compiled with tsc
import { hc } from 'hono/client'
import { app } from './app'
const client = hc<typeof app>('')
export type Client = typeof client
export const hcWithType = (...args: Parameters<typeof hc>): Client => hc<typeof app>(...args)
22. What did 4.11 and 4.12 add to the RPC client?
Several typed helpers that remove hand-written glue:
$url() returns a URL; since 4.11.0, passing the base URL as a second type parameter (hc<AppType, 'http://localhost:8787'>) makes it a precise typed URL, useful as an SWR or TanStack Query key.
$path() (4.12.0) returns only the path string, with params and query filled in, independent of the base URL.
ApplyGlobalResponse (4.12.0) adds error shapes from onError or global middleware, such as 401 and 500 bodies, to every route's response type.
parseResponse() (4.9.0) parses the body by content type and throws a DetailedError when the response is not ok.
- Custom
NotFoundResponse (4.11.0) through module augmentation, so c.notFound() has a typed body on the client.
buildSearchParams (4.11.0) customizes query serialization, for APIs that expect tags[]=a&tags[]=b.
A candidate does not need every helper by name. You are checking whether they know the client can be typed end to end, including errors, without an OpenAPI generator.
23. When would you choose OpenAPI over Hono RPC?
RPC works when the client is TypeScript and lives in the same repository or monorepo as the server, so the type import is cheap.
It does not help a mobile app in Swift or Kotlin, a partner integration, or any consumer that needs a published contract and versioning.
For public or multi-language APIs, generate an OpenAPI document from the same schemas, for example with the @hono/zod-openapi package from the Hono middleware repository, and keep the RPC client for the internal web app.
A strong candidate states the trade-off in both directions: RPC couples the client to the server's TypeScript types and Hono version, while OpenAPI adds a schema to maintain but survives a language change on either side.