Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Honoとフロントエンドの 型安全性について

yodaka
February 17, 2025

Honoとフロントエンドの 型安全性について

yodaka

February 17, 2025
Tweet

Other Decks in Programming

Transcript

  1. 自己紹介 よだか - フリーランス、WebDeveloper - Next.js / Hono / Laravel

    / Vue.js / TypeScript - 最近Flutterも - TSKaigiスタッフ - 開催:2025年5月23日-24日 2Days - 会場:ベルサール神田 - 趣味で音楽を作ってます - 映画や小説が好き
  2. What’s Hono?(ちょっとだけ) - ランタイム差異を吸収するポータビリティ - > Cloudflare Workers, Fastly Compute,

    Deno, Bun, AWS Lambda,... - Web標準 - https://wintercg.org/(WinterTC) - 軽量・高速 - > Hono x 402,820 ops/sec ±4.78% (80 runs sampled) - > The hono/tiny preset is under 14kB. Hono has zero dependencies and uses only the Web Standards. - 豊富なミドルウェア、カスタマイズ性 - CORS、CSRF、JWT、Logger… - RPCやミドルウェアを使った、フロントエンドとの型共有
  3. What’s Hono?(ちょっとだけ) - ランタイム差異を吸収するポータビリティ - > Cloudflare Workers, Fastly Compute,

    Deno, Bun, AWS Lambda,... - Web標準 - https://wintercg.org/(WinterTC) - 軽量・高速 - > Hono x 402,820 ops/sec ±4.78% (80 runs sampled) - > The hono/tiny preset is under 14kB. Hono has zero dependencies and uses only the Web Standards. - 豊富なミドルウェア、カスタマイズ性 - CORS、CSRF、JWT、Logger… - RPCやミドルウェアを使った、フロントエンドとの型共有  ←ココ
  4. HonoのAPI定義 const adminRouter = new Hono().post( '/posts', zValidator( 'json', z.object({

    title: z.string(), body: z.string(), }) ), (c) => { // 型がついている const { title, body } = c.req.valid(‘json’) } ) type Form = { title: string body: string }
  5. Honoからエクスポートした型をNext.jsに渡す(Hono側) const app = new Hono() .route('/sp', spRouter) .route('/web', webRouter)

    .route('/admin', adminRouter) export type AdminAppType = typeof adminRouter export type webRouter = typeof webRouter
  6. Honoからエクスポートした型をNext.jsに渡す(Next.js 側) import { hc } from 'hono/client' import {

    AdminAppType } from 'backend/src' // typesafeなAPIClientとして使える。 const client = hc<AdminAppType>(baseUrl, { headers, })
  7. Honoからエクスポートした型をNext.jsに渡す // クライアント import { hc } from 'hono/client' import

    { AdminAppType } from 'backend/src' // typesafeなAPIClientとして使える。 const client = hc<AdminAppType>(baseUrl, { headers, }) // サーバー const app = new Hono() .route('/sp', spRouter) .route('/web', webRouter) .route('/admin', adminRouter) export type AdminAppType = typeof adminRouter export type webRouter = typeof webRouter
  8. Next.js側 APIクライアント使用例 // パスも型がついている const res = await client.posts.$post({ json:

    { // request bodyも型がついてる title: 'Hello', body: 'Hono is a cool project', }, }) type Form = { title: string body: string }
  9. 引用・参考文献 - Hono 公式ドキュメント - https://hono.dev/ - TRPC 公式ドキュメント -

    https://trpc.io/ - SWRのサンプル - https://github.com/yodakaEngineer/hono-swr-example - 構成参考記事 - https://zenn.dev/yodaka/articles/ad49f29a54ceba