Hono fullstack
A notes app with its backend in the same project. Vite serves the React app and runs the Hono API under /api, and the
client gets every type from the Hono routes, without codegen.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";
import { sdk } from "./api";
export const App = () => {
const [text, setText] = useState("");
// `data` is typed as `Note[]` by the GET /api/notes handler in server/app.ts.
const { data, error, loading, refetch } = useFetch(sdk.api.notes.$get);
const { submit, submitting, error: submitError, onSubmitSuccess } = useSubmit(sdk.api.notes.$post);
onSubmitSuccess(() => {
setText("");
refetch();
});
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
// The payload type comes from the route's `json` validator.
submit({ payload: { text } });
};
const remove = async (noteId: number) => {
// `:noteId` in the Hono path types `setParams()`.
const response = await sdk.api.notes.$noteId.$delete.setParams({ noteId }).send();
if (response.success) refetch();
};
return (
<main className="container">
<hgroup>
<h1>Notes</h1>
<p>A Hono API and a React client in one Vite app. The client types come from the server routes.</p>
</hgroup>
<form onSubmit={handleSubmit}>
<fieldset role="group">
<input
value={text}
onChange={(event) => setText(event.target.value)}
placeholder="New note"
aria-invalid={submitError ? true : undefined}
/>
<button type="submit" aria-busy={submitting} disabled={submitting}>
Add
</button>
</fieldset>
{/* The server answers an empty note with 400 and `{ message }`, the error type of the client. */}
{submitError && <small className="error">{submitError.message}</small>}
</form>
{loading && !data && <p aria-busy="true">Loading notes...</p>}
{error && <p className="error">Could not load notes: {error.message}</p>}
<ul className="list">
{data?.map((note) => (
<li key={note.id}>
<span>
{note.text}
<br />
<small className="muted">{new Date(note.createdAt).toLocaleString()}</small>
</span>
<button type="button" className="outline secondary" onClick={() => remove(note.id)}>
Delete
</button>
</li>
))}
</ul>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/hono/fullstack hyper-fetch-hono-fullstack && cd hyper-fetch-hono-fullstack && npm install && npm run devHonoSchematurns the type of a Hono app into a schema forcreateSdk.- Typed from the routes: responses, the
jsonvalidator payload and:noteIdparams all reach the client. - One dev server:
@hono/vite-dev-serverruns the API inside Vite, sonpm run devstarts both. - Typed errors: the server sends
{ message }, the error type of the HyperFetch client.
How it works
-
server/app.tsdefines the routes as one chain underbasePath("/api")and exports the schema type next to the app:export type AppSchema = HonoSchema<typeof app>; -
vite.config.tsaddsdevServer({ entry: "server/app.ts", exclude: [...] }). Requests to/apigo to the Hono app; everything else is served by Vite.vite buildbuilds only the client, so in production the API runs wherever you deploy Hono. -
src/api.tsimportsAppSchemawithimport type, so no server code reaches the browser bundle, and callscreateSdk<typeof client, AppSchema>(client).sdk.api.notes.$get,sdk.api.notes.$postandsdk.api.notes.$noteId.$deleteare regular requests. -
Appreads the list withuseFetch(sdk.api.notes.$get), adds notes withuseSubmit(sdk.api.notes.$post)and deletes them withsdk.api.notes.$noteId.$delete.setParams({ noteId }).send(). Change a route inserver/app.tsand TypeScript points at the client code that no longer matches. -
The
jsonvalidator throws anHTTPExceptionfor an empty note, andonErrorturns it into{ message }with a400.useSubmitreturns it aserror. Throwing keeps the error body out of the route's response type, which staysNote.
- Projects with a Hono backend and a TypeScript frontend, in one repository.
- Teams that want end-to-end types without generating a client.
- Small fullstack apps that should start with a single
npm run dev.
Related
HonoSchema reads the Hono app type and createSdk turns it into typed requests. The backend stays the single
source of truth, and the frontend uses the same hooks as any other HyperFetch app.
