Skip to content

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

@Soviut

Description

@Soviut

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions