middleware icon indicating copy to clipboard operation
middleware copied to clipboard

zod-validator should show a more useful error when JSON body is missing content-type header

Open Soviut opened this issue 1 year ago • 4 comments

I created a very simple zod-validator to use in my test suite.

import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'

export const testBodyValidator = zValidator(
  'json',
  z.object({
    key: z.string().min(1),
  })
)

My route looked like

router.post('/', testBodyValidator, async (c) => {
  return c.json(c.req.valid('json'))
})

My test looked like this

describe('POST /testing', () => {
  it('should return the request body', async () => {
    const res = await app.request('/testing', {
      method: 'POST',
      body: JSON.stringify({ key: 'value' }),
    })
    expect(await res.json()).toStrictEqual({ key: 'value' })
  })
})

However, I kept getting errors about the key field being missing.

After hours of debugging I noticed one example had the content-type header set in the app.request()

      headers: new Headers({ 'Content-Type': 'application/json' }),

That turns out to be what the problem was. While I understand why it happened, it wasn't obvious that was the issue. It would be really useful if zValidator could return an error if the validation target is json but the content-type header is missing or does not contain application/json.

Soviut avatar Nov 20 '24 07:11 Soviut

@Soviut Hello. This behavior is due to the hono/validator implementation, not zValidator. However, it may indeed be a good idea to print a warning.

sushichan044 avatar Nov 27 '24 04:11 sushichan044

If you want to show an error message, you can add a code here:

https://github.com/honojs/hono/blob/main/src/validator/validator.ts#L74-L76

We should not make it throw an error, but it's better to show a message with console.log() or console.warn().

yusukebe avatar Nov 28 '24 01:11 yusukebe

That sounds good 👀

sushichan044 avatar Nov 28 '24 02:11 sushichan044

I've added the PR here https://github.com/honojs/hono/pull/3707 and a docs update here https://github.com/honojs/website/pull/540

Soviut avatar Nov 28 '24 03:11 Soviut