h3 icon indicating copy to clipboard operation
h3 copied to clipboard

feat(handler): new `defineJsonRpcHandler`

Open sandros94 opened this issue 4 months ago • 4 comments

An experimental handler to support the JSON RPC spec.

Usage

you define it like a normal handler, but with the added params as its first callback argument:

const eventHandler = defineJsonRpcHandler({
  echo: (params, event) => {
    return `Recieved \`${params}\` on path \`${event.url.pathname}\``;
  },
});
app.post("/rpc"; eventHandler); // Must be a POST method

then you call it with a valid body, for example:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "echo",
  "params": "Hello World",
}

and you'll receive a json-rpc compatible response:

{
  "jsonrpc": "2.0",
  "id": 1, // Same id from the request
  "result": "Recieved `Hello World` on path `/rpc`",
}

it also support client-to-server notifications by simply omitting the id key, this will result in the server responding a 202

Personal considerations and future expansion

  • Support built-in schema validation (probably allowing for an object instead of directly the event callback)

sandros94 avatar Aug 02 '25 11:08 sandros94

Codecov Report

:x: Patch coverage is 91.94631% with 12 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/utils/json-rpc.ts 91.89% 12 Missing :warning:

:loudspeaker: Thoughts on this report? Let us know!

codecov[bot] avatar Aug 02 '25 11:08 codecov[bot]

Deploying h3dev with  Cloudflare Pages  Cloudflare Pages

Latest commit: 4d0d8c0
Status: ✅  Deploy successful!
Preview URL: https://d4d2748b.h3dev.pages.dev
Branch Preview URL: https://feat-json-rpc-handler.h3dev.pages.dev

View logs

Hi dear @sandros94 This PR is under my radar (and important!) but have to delay for more testing. In meantime you don't need to keep it updated ❤️

pi0 avatar Aug 27 '25 14:08 pi0

Hi dear @sandros94 This PR is under my radar (and important!) but have to delay for more testing. In meantime you don't need to keep it updated ❤️

Absolutely no problem, I also imagine that we all took some time off for the summer and should focus on more important things first, this is a long term one. This feature is also easy to implement in downstream projects, so no rush.

The reason why I kept updating it for a bit was because while testing it with some Json RPC clients (mainly MCP-related ones) I've found a couple of issues and DX improvements, but now it is complete for what I know atm

sandros94 avatar Aug 27 '25 15:08 sandros94