🔥

HonoでConnect RPCを動かす

に公開

こんにちは、@sugar235711です。
この記事は「Hono Advent Calendar 2025」15日目の記事です。
https://qiita.com/advent-calendar/2025/hono

はじめに

HonoのNode.js Adapterを使うと、HTTP/2通信を行うサーバーを簡単に立ち上げることができます。

https://hono.dev/docs/getting-started/nodejs#http2

import { createServer } from 'node:http2'

const server = serve({
  fetch: app.fetch,
  createServer,
})

なのでHonoで立ち上げたNode.jsサーバー上でConnect RPCを使ったgRPC互換のサーバー動かせますよね。ということで試しました。

検証用のコードは↓
https://github.com/sugar-cat7/hono-connect-example/tree/main

Connect RPCについて

Connect RPCは、gRPC/gRPC-Web/Connect Protocolの3つのプロトコルで通信できるRPCフレームワークです。TypeScript/JavaScriptをはじめ、Go、Python、Java、C#等様々な言語で利用可能です。
Protocol Buffersを使用してスキーマ定義し、型安全なRPC通信を実現します。
この記事はHonoの記事なのでこれ以上は割愛します。
https://connectrpc.com/

筆者のConnect RPC関連記事
connect-es編
connect-go から学ぶコード生成
gRPCとフロントエンド_Connectを添えて

Hono用ミドルウェアの作成

HonoでConnect RPCを使うために、honoConnectMiddlewareを作成します。Express用のミドルウェアを参考に実装しています。

https://github.com/sugar-cat7/hono-connect-example/blob/main/lib/middleware.ts

ポイントは以下の通りです。

・Node.jsリクエスト/レスポンスの変換: universalRequestFromNodeRequestとuniversalResponseToNodeResponseを使用して、HonoのNode.js環境とConnect RPCのUniversal Handlerを橋渡しの実装
・コンテキストの受け渡し: HonoのContextをConnect RPCのContextに渡すための仕組みの実装

Node.jsリクエスト/レスポンスの変換

HonoのNode.js Adapterでは、incoming/outgoingでリクエスト/レスポンスを扱います。

https://github.com/honojs/node-server/blob/76d80e6c1c7bf7101b80392b6bfacc17e3829fd9/src/types.ts#L23-L31

Connect RPCのUniversal Handlerと連携するには、これらを変換する必要があります。Connect側が提供するuniversalRequestFromNodeRequestとuniversalResponseToNodeResponseを使って変換を行います。

https://github.com/sugar-cat7/hono-connect-example/blob/6790b1941720f9584bbbe875458a30860bd5e1e5/lib/middleware.ts#L92-L101

コンテキストの受け渡し

利用側は簡単で、Connect RPC用のRouterを作成してミドルウェアに渡すだけです。

const honoContextKey = createHonoContextKey<HonoEnv>();
const app = new Hono<HonoEnv>();

app.use("*", requestId());

// Connect RPC エンドポイント
app.use(
  "/connectrpc*",
  honoConnectMiddleware({
    honoContextKey,
    routes(router: ConnectRouter) {
      router.service(ElizaService, {
        say(req: SayRequest, ctx) {
          // HonoのContextからrequestIdを取得
          const honoCtx = ctx.values.get(honoContextKey);
          const reqId = honoCtx?.get("requestId");
          return create(SayResponseSchema, {
            sentence: `You said: "${req.sentence}" (requestId: ${reqId})`,
          });
        },
      });
    },
  })
);

// 通常のRESTエンドポイント
app.get("/", (c) => c.text("Hello Hono with Connect RPC over HTTP/2!"));
app.get("/api/users", (c) => c.json({ users: [{ id: 1, name: "John" }] }));

そのままだとConnect RPCのRouter側にHonoのContextが渡せないので、createHonoContextKeyというSymbolを使ってHonoのContextをConnectのContextに渡しています。

export function createHonoContextKey<E extends Env>() {
  return createContextKey<Context<E> | undefined>(undefined);
}

これによりHonoのミドルウェアで設定した値(例:requestId)をConnect RPCのサービス実装側で取得できるようにします。

HTTP/2サーバーの起動

あとは適当に証明書を用意してサーバーを立ち上げれば、HTTP/2での通信が可能になります。

serve({
  fetch: app.fetch,
  port: 3000,
  createServer: createSecureServer,
  serverOptions: {
    key: readFileSync("certs/server.key"),
    cert: readFileSync("certs/server.crt")
  },
});

Connect Protocol(JSON)での通信

$ curl -k -v --http2 https://localhost:3000/connectrpc.eliza.v1.ElizaService/Say \
  -H "Content-Type: application/json" \
  -d '{"sentence": "Hello!"}'

* using HTTP/2
* [HTTP/2] [1] OPENED stream for https://localhost:3000/connectrpc.eliza.v1.ElizaService/Say
> POST /connectrpc.eliza.v1.ElizaService/Say HTTP/2
> Content-Type: application/json
< HTTP/2 200 
< content-type: application/json
{"sentence":"You said: \"Hello!\" (requestId: 57a7bfde-12c0-49fd-bb4d-dd0994fd241a)"}

gRPCプロトコルでの通信

gRPC互換なのでcontent-type: application/grpc+protoでの通信も可能です。

$ grpcurl \
  -insecure \
  -protoset eliza.protoset \
  -d '{"sentence":"Hello!"}' \
  localhost:3000 \
  connectrpc.eliza.v1.ElizaService/Say

{
  "sentence": "You said: \"Hello!\" (requestId: dd1b21d6-7c36-4df5-91e5-dd0ac9e497d0)"
}

unaryのみしか試してないですが、Node.jsサーバーならStreamingも動作するはずです。
もちろん既存のHono APIと共存できるため、ソフトウェアレイヤーでの REST APIとgRPCのゲートウェイサーバーとして利用できたり、gRPC Webとも互換があるので何も考えず(???)にブラウザでも使えます。

まとめ

HonoとConnect RPCを組み合わせて開発ができます。

Discussion