Elysia fullstack
A bookmarks app with an Elysia backend running on Node.js. The React client filters, adds and deletes bookmarks through
an SDK typed from the Elysia routes: query params, payloads, responses, the 422 validation error and a custom 404.
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 { client, sdk } from "./api";
const tags = ["docs", "tools"] as const;
type Tag = (typeof tags)[number];
export const App = () => {
const [filter, setFilter] = useState<Tag | undefined>(undefined);
const [form, setForm] = useState({ title: "", url: "", tag: "docs" as Tag });
const [deleteError, setDeleteError] = useState<string | null>(null);
// `setQueryParams` is typed by the route's `query` schema.
const { data, error, loading } = useFetch(sdk.api.bookmarks.$get.setQueryParams({ tag: filter }));
const { submit, submitting, error: createError, onSubmitSuccess } = useSubmit(sdk.api.bookmarks.$post);
// Every tag filter is its own cache entry, so refresh all of them after a change.
const refreshLists = () => client.cache.invalidate(/\/api\/bookmarks/);
onSubmitSuccess(() => {
setForm((current) => ({ ...current, title: "", url: "" }));
refreshLists();
});
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
// The payload type comes from the route's `body` schema.
submit({ payload: form });
};
const remove = async (bookmarkId: number) => {
const response = await sdk.api.bookmarks.$bookmarkId.$delete.setParams({ bookmarkId }).send();
// The error is typed as the route's `status(404, { message })` body, or the client's global `Error`.
setDeleteError(response.error?.message ?? null);
refreshLists();
};
return (
<main className="container">
<hgroup>
<h1>Bookmarks</h1>
<p>An Elysia API on Node.js and a React client typed from its routes.</p>
</hgroup>
<form onSubmit={handleSubmit}>
<fieldset className="grid">
<input
value={form.title}
onChange={(event) => setForm({ ...form, title: event.target.value })}
placeholder="Title"
/>
<input
value={form.url}
onChange={(event) => setForm({ ...form, url: event.target.value })}
placeholder="https://..."
/>
<select
value={form.tag}
onChange={(event) =>
setForm({
...form,
tag: tags.find((tag) => tag === event.target.value) ?? "docs",
})
}
>
{tags.map((tag) => (
<option key={tag}>{tag}</option>
))}
</select>
<button type="submit" aria-busy={submitting} disabled={submitting}>
Add
</button>
</fieldset>
{/* A schema failure answers 422 with `{ property, summary }`, typed as the local error. */}
{createError && "summary" in createError && (
<small className="error">
{createError.summary} ({createError.property})
</small>
)}
</form>
<div role="group">
<button type="button" className={filter ? "outline" : undefined} onClick={() => setFilter(undefined)}>
all
</button>
{tags.map((tag) => (
<button
key={tag}
type="button"
className={filter === tag ? undefined : "outline"}
onClick={() => setFilter(tag)}
>
{tag}
</button>
))}
</div>
{loading && !data && <p aria-busy="true">Loading bookmarks...</p>}
{error && <p className="error">Could not load bookmarks: {error.message}</p>}
{deleteError && <p className="error">{deleteError}</p>}
<ul className="list">
{data?.map((bookmark) => (
<li key={bookmark.id}>
<span>
<a href={bookmark.url} target="_blank" rel="noreferrer">
{bookmark.title}
</a>{" "}
<mark>{bookmark.tag}</mark>
</span>
<button type="button" className="outline secondary" onClick={() => remove(bookmark.id)}>
Delete
</button>
</li>
))}
</ul>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/elysia/fullstack hyper-fetch-elysia-fullstack && cd hyper-fetch-elysia-fullstack && npm install && npm run devElysiaSchematurns the type of an Elysia app into a schema forcreateSdk, with no codegen.- Typed inputs: the
queryschema typessetQueryParams(), thebodyschema types the payload, and:bookmarkIdtypessetParams(). - Typed errors: Elysia rejects bad input with a
422before the handler runs, and the client reads itssummaryandpropertywith types. - Elysia on Node.js with
@elysiajs/node, started next to Vite by onenpm run dev.
How it works
-
server/app.tscreates the app withnew Elysia({ adapter: node(), prefix: "/api" })and chains every route, since Elysia only types the routes of one chain. It exports the schema type next to the app:export type AppSchema = ElysiaSchema<typeof app>; -
vite.config.tshas a small plugin that loadsserver/app.tswithssrLoadModule, callsapp.listen(3000)and restarts it when a file inserver/changes.server.proxyforwards/apito it, so the page calls its own origin. In production, run the API alone withnpm run api(server/index.ts) and build the client withvite build. -
src/api.tsimportsAppSchemawithimport typeand callscreateSdk<typeof client, AppSchema>(client). The/apiprefix becomessdk.api, sosdk.api.bookmarks.$getisGET /api/bookmarks. -
Appreads the list withuseFetch(sdk.api.bookmarks.$get.setQueryParams({ tag: filter })). Passing a tag that is notdocsortoolsdoes not compile, because the route'squeryschema says so. -
Submit the form with an empty title or a URL like
not-a-url. Thebodyschema fails, Elysia answers422, and the form showscreateError.summary. A"summary" in createErrorcheck separates that body from a network error. -
sdk.api.bookmarks.$bookmarkId.$delete.setParams({ bookmarkId }).send()returnsstatus(404, { message })as its typed error when the bookmark is gone. After every change,client.cache.invalidate(/\/api\/bookmarks/)refreshes all cached filters.
- You use Elysia and want end-to-end types plus caching, retries and React hooks on the client.
- Your Elysia API runs on Node.js today and may move to Bun later. The schema is a type, so the client does not change.
Related
ElysiaSchema reads the routes and schemas of an Elysia app and createSdk turns them into typed requests.
Query params, payloads, responses and error bodies all follow the backend, and the frontend uses the usual hooks.
