Skip to main content

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.

intermediateelysiacreateSdktypescriptvalidationerrors
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/elysia/fullstack hyper-fetch-elysia-fullstack && cd hyper-fetch-elysia-fullstack && npm install && npm run dev
What it shows
  1. ElysiaSchema turns the type of an Elysia app into a schema for createSdk, with no codegen.
  2. Typed inputs: the query schema types setQueryParams(), the body schema types the payload, and :bookmarkId types setParams().
  3. Typed errors: Elysia rejects bad input with a 422 before the handler runs, and the client reads its summary and property with types.
  4. Elysia on Node.js with @elysiajs/node, started next to Vite by one npm run dev.

How it works​

  1. server/app.ts creates the app with new 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>;
  2. vite.config.ts has a small plugin that loads server/app.ts with ssrLoadModule, calls app.listen(3000) and restarts it when a file in server/ changes. server.proxy forwards /api to it, so the page calls its own origin. In production, run the API alone with npm run api (server/index.ts) and build the client with vite build.

  3. src/api.ts imports AppSchema with import type and calls createSdk<typeof client, AppSchema>(client). The /api prefix becomes sdk.api, so sdk.api.bookmarks.$get is GET /api/bookmarks.

  4. App reads the list with useFetch(sdk.api.bookmarks.$get.setQueryParams({ tag: filter })). Passing a tag that is not docs or tools does not compile, because the route's query schema says so.

  5. Submit the form with an empty title or a URL like not-a-url. The body schema fails, Elysia answers 422, and the form shows createError.summary. A "summary" in createError check separates that body from a network error.

  6. sdk.api.bookmarks.$bookmarkId.$delete.setParams({ bookmarkId }).send() returns status(404, { message }) as its typed error when the bookmark is gone. After every change, client.cache.invalidate(/\/api\/bookmarks/) refreshes all cached filters.

When to use it
  • 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.

Summary

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.