github honojs/hono v2.6.0

latest releases: v4.6.2, v4.6.1, v4.6.0...
21 months ago

Summary

This release includes the new feature for adavanced users, it will be important in the future!!

BREAKING CHANGE

c.req.cookie() now returns string | undefined. This may cause a Type error.

You can use 3rd party libs for the validation

It become to allow normal types, instead of only allowing Schema in the Handler.

type User = {
  id: string
  name: string
  age: number
}

const handler: Handler<User> = (c) => {
  const user = c.req.valid() // <--- user is User
  // ...
}

This change also makes it possible to use the 3rd party library such as "Zod" for validation.

import { Hono } from 'hono'
import type { Handler } from 'hono'
import { z } from 'zod'
import type { ZodType } from 'zod'

const app = new Hono()

const schema = z.object({
  id: z.string(),
  name: z.string(),
  age: z.number(),
})

// You can write a custom validator with Zod:
const zValidtor = <T extends ZodType>(schema: T): Handler<z.infer<T>> => {
  return async (c, next) => {
    const parsed = schema.safeParse(await c.req.json())
    if (!parsed.success) {
      return c.text('Invalid!', 400)
    }
    c.req.valid(parsed.data)
    await next()
  }
}

app.post('/post', zValidtor(schema), (c) => {
  const user = c.req.valid() // <--- user will be `User`
  return c.json(user)
})

Builtin Validator is recommended, but if developers want to use Zod, they can.

And this feature will be important in the future!!

What's Changed

New Contributors

Full Changelog: v2.5.10...v2.6.0

Don't miss a new hono release

NewReleases is sending notifications on new releases.