Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

hono-rpc

БесплатноБез исполняемых скриптовНе проверен

Hono RPC shares a Hono server's route types with a typed fetch client (hc), giving end-to-end type safety for REST APIs without code generation or schema…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Hono RPC

Overview

Hono RPC links a Hono server and its clients through types. Routes with validators are written on the server, the app's type is exported as AppType, and the hc<AppType>() client from hono/client then knows every path, method, input and JSON response. The client is a thin wrapper over fetch; nothing is generated. Type inference only sees what the chain of route definitions exposes, so most pitfalls below are about keeping that chain intact.

Instructions

Install

npm install hono zod @hono/zod-validator
npm install @hono/node-server        # only when running on Node.js

On Bun and Cloudflare Workers hono is enough for the server. On Deno import jsr:@hono/hono. Set "strict": true in the tsconfig.json of both server and client (in a monorepo, of every package); without it the inferred types degrade. The validator also works with Standard Schema libraries such as Valibot through @hono/standard-validator.

Define routes and export the type

Chain the handlers (new Hono().get(...).post(...)) so each call adds to the type, and export typeof the final value:

// src/server.ts
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";

const createUser = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
});

const users = new Hono()
  .get("/", (c) => c.json({ users: [{ id: 1, name: "Maria Lopez", email: "[email protected]" }] }))
  .get("/:id", (c) => {
    const id = Number(c.req.param("id"));
    if (id !== 1) return c.json({ error: "User not found" }, 404);
    return c.json({ user: { id, name: "Maria Lopez" } }, 200);
  })
  .post("/", zValidator("json", createUser), (c) => {
    const data = c.req.valid("json"); // typed from the schema
    return c.json({ user: { id: 2, ...data } }, 201);
  })
  .patch("/:id", zValidator("json", createUser.partial()), (c) => {
    return c.json({ user: { id: Number(c.req.param("id")), ...c.req.valid("json") } });
  })
  .delete("/:id", (c) => c.json({ deleted: Number(c.req.param("id")) }));

const app = new Hono().route("/users", users);

export type AppType = typeof app;
export default app;

Run it on Node.js with import { serve } from "@hono/node-server"; serve({ fetch: app.fetch, port: 3000 });. Bun and Workers use the default export directly.

Call it from the client

import { hc } from "hono/client";
import type { AppType } from "./server"; // type-only import: no server code ships to the browser

const client = hc<AppType>("http://localhost:3000");

const list = await client.users.$get();
if (list.ok) console.log((await list.json()).users);

const created = await client.users.$post({ json: { name: "Tom Becker", email: "[email protected]", age: 30 } });
const one = await client.users[":id"].$get({ param: { id: "1" } });
await client.users[":id"].$patch({ param: { id: "1" }, json: { name: "Tom B." } });
await client.users[":id"].$delete({ param: { id: "1" } });

Path parameters and query values must be passed as strings even when the schema turns them into numbers. hc does not URL-encode param; wrap values that may contain / in encodeURIComponent, or declare the route with a regexp such as /files/:name{.+}.

Query, headers, cookies, abort

const search = new Hono().get(
  "/search",
  zValidator("query", z.object({ q: z.string().optional(), page: z.coerce.number().default(1) })),
  (c) => c.json({ results: [], ...c.req.valid("query") }),
);

type SearchApp = typeof search;
const client = hc<SearchApp>("http://localhost:3000", {
  headers: { Authorization: `Bearer ${process.env.API_TOKEN}` }, // sent with every call
  init: { credentials: "include" },                               // send cookies
});
const res = await client.search.$get({ query: { q: "hono", page: "2" } });
const withId = await client.search.$get({ query: { q: "x" } }, { headers: { "X-Request-ID": crypto.randomUUID() } });

Per-call options (second argument) accept headers and init (a RequestInit, for example { signal } to abort; init wins over other options). Other validator targets are form, param, header and cookie; file uploads go through form with a File.

Status codes and errors

Give c.json() an explicit status so the client can narrow on it. Do not use c.notFound() in an RPC route: its body is untyped and the client sees unknown. Return c.json({ error: "..." }, 404) instead.

const res = await client.users[":id"].$get({ param: { id: "999" } });
if (res.status === 404) console.error((await res.json()).error);
if (res.ok) console.log((await res.json()).user);

Errors thrown with HTTPException or returned by app.onError() and global middleware are not part of the inferred types. Wrap the type with ApplyGlobalResponse from hono/client to add them: `hc<ApplyGlobalResponse<typeof app, { 500: { json: { error: string } } }>>(ur

Полный SKILL.md на GitHub

Установить hono-rpc в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл hono-rpc?

Hono RPC shares a Hono server's route types with a typed fetch client (hc), giving end-to-end type safety for REST APIs without code generation or schema files. Use when building a type-safe API with Hono, sharing API types between frontend and backend, validating input with Zod and getting the types on the client, or replacing tRPC with plain REST. Runs on Cloudflare Workers, Deno, Bun and Node.js.

Как установить скилл hono-rpc?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл hono-rpc запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить hono-rpc с