Migrating from TanStack Start
These tables map TanStack Start (with TanStack Router) to Hamur: route files, route options, server functions, search params and middleware. The tables on the server in Migrating from Nuxt apply to any app. Each row has a status: same (the name and the behaviour carry over), different (Hamur has the feature under another name or shape; the row says how) and none (Hamur has no equivalent today).
There is no hamur migrate command for TanStack Start: the move is by hand, route by route, with the tables below. Keep react and react-dom. For TanStack Query, see the TanStack Query recipe.
The shape is one thing in Hamur: a handler, a typed function that runs on the server, exported from server/index.ts. A component calls it (useAction(fn), useAsyncData(fn, input)), a load calls it, a form posts to it (Form action={fn}), and with a route a URL answers it. It is a public endpoint that must check who calls it.
Step by step
- Install Hamur:
bun remove @tanstack/react-start @tanstack/react-router, thenbun add hamur @hamur/adapter-react. - Write
hamur.config.tswithdefineConfig({ framework: "react" }). Vite plugins are covered in Vite plugins. - Move each file of
src/routes/toapp/pages/, using the tables below.__root.tsxbecomesapp/app.tsxand a layout. - Split each
createFileRoutecall into its files: the component stays in the page,loaderbecomes aloadthat calls a handler, eachcreateServerFnbecomes a handler. - Run
hamur dev, open each page, thenhamur build.
Route files
{path} is the folders under app/pages/.
| TanStack Start | Hamur | Status | Differences | Docs |
|---|---|---|---|---|
src/routes/index.tsx | app/pages/index.tsx | same | Routing | |
posts.$postId.tsx, posts/$postId.tsx | app/pages/posts/[postId].tsx | different | $param becomes [param], and a dotted name is a folder | Routing |
$.tsx (a splat) | app/pages/[...path].tsx | different | [...path] never matches an empty path; use [[...path]] for that | Routing |
_authed.tsx (a pathless layout route) | (authed).tsx beside the folder (authed)/ | different | the group adds nothing to the path | Routing |
posts.tsx with <Outlet /> | posts.tsx beside the folder posts/, with Outlet | same | Routing | |
__root.tsx and createRootRoute | app/app.tsx, app/layouts/default.tsx and app.head of hamur.config.ts | different | Hamur writes <html>, <head> and <body> | Routing |
createFileRoute("/posts/$postId") | the file path | different | there is no route-id string to keep in sync; hamur typegen types the route | Data |
routeTree.gen.ts | .hamur/ | different | generated by hamur typegen; never edited | TypeScript |
router.tsx with createRouter | app/router.options.ts | different | router options only; Hamur creates the router | Routing |
| virtual file routes | a route table in code | different | Routing |
Route options
A route is one createFileRoute call with options. In Hamur the options are spread over the files of the route.
| TanStack Start | Hamur | Status | Differences | Docs |
|---|---|---|---|---|
component | export default of the page file | same | Routing | |
loader | load in x.load.ts, calling a handler | different | the server code is the handler | Data |
Route.useLoaderData() | useData() from @hamur/adapter-react | different | type it with useData<T>() | Data |
Route.useParams() | useRoute().params | different | a catch-all param is a string[] | Routing |
Route.useSearch() | useSearch() from @hamur/adapter-react | different | returns { value, set } | Routing |
validateSearch | export const search, a Standard Schema | different | Zod, Valibot and ArkType schemas work as they are; an invalid query answers 400 | Routing |
loaderDeps | export const searchKeys in the page's x.load.ts | different | an array of string literals; only those keys re-run the load | Data |
beforeLoad | route middleware | different | a function the page imports and passes in meta.middleware; it steers and guards no data | Routing |
context and beforeLoad returning a context | none | none | pass what a page needs through useData(), or read it in a handler | Data |
head, meta, links | useHead from @hamur/adapter-react, or head in the page's meta | different | Head | |
errorComponent | x.error.tsx beside the page, or _error.tsx in a folder | different | it reads the error with useError() and leaves with clearError() | Routing |
notFoundComponent | x.not-found.tsx beside the page, or _not-found.tsx | different | Routing | |
pendingComponent | x.pending.tsx beside the page, or _pending.tsx | different | it shows after 1000 ms of a client navigation | Routing |
staleTime, gcTime | meta.staleTime, meta.gcTime | same | the client data cache of the page | Data |
ssr: false | meta.ssr | different | false renders the page in the browser only | Routing |
redirect({ to }) | redirect(to) from hamur/app | same | returned or thrown; another origin needs { external: true } | Routing |
notFound() | notFound() from hamur/app | same | Errors | |
router.invalidate() | useRouter().refresh() | different | refresh(key) re-runs the loads that declared the key | Data |
useNavigate() | useRouter().navigate(to, { replace }) | different | Navigation | |
<Link to params search> | Link from @hamur/adapter-react | different | to is the path; query takes an object or (prev) => next | Navigation |
Await and a deferred loader value | none | none | a slow part is a useAsyncData call below the page | Data |
useRouterState() | useRoute() and useNavigation() | different | API: adapters |
A route, converted
A route with a loader, a validateSearch and a server function becomes a handler file, a load, a page and a search schema. A handler runs only on the server and is a public endpoint, so it checks its input.
import { createError, defineHandler } from "hamur/server"
import { schema } from "./schema.ts"
const posts = new Map([["hello", { id: "hello", title: "Hello", body: "First post" }]])
const idInput = schema<{ id: string }>(
{ type: "object", properties: { id: { type: "string" } }, required: ["id"] },
(value) => {
const id = (value as { id?: unknown } | undefined)?.id
return typeof id === "string" && id
? { value: { id } }
: { issues: [{ message: "An id is required", path: ["id"] }] }
},
)
const newPost = schema<{ id: string; title: string }>(
{ type: "object", properties: { id: { type: "string" }, title: { type: "string" } }, required: ["id", "title"] },
(value) => {
const { id, title } = (value ?? {}) as { id?: unknown; title?: unknown }
if (typeof id !== "string" || !id) return { issues: [{ message: "An id is required", path: ["id"] }] }
return typeof title === "string" && title
? { value: { id, title } }
: { issues: [{ message: "A title is required", path: ["title"] }] }
},
)
export const getPost = defineHandler({
method: "GET",
input: idInput,
handler({ id }) {
const post = posts.get(id)
if (!post) throw createError({ status: 404, message: "Post not found" })
return post
},
})
export const listPosts = defineHandler({
method: "GET",
handler: () => [...posts.values()],
})
export const createPost = defineHandler({
input: newPost,
handler({ id, title }) {
const post = { id, title, body: "" }
posts.set(id, post)
return post
},
})
export { createPost, getPost, listPosts } from "./posts.ts"
export { webhook } from "./webhook.ts"
The loader is a load that calls the handler. Route.useLoaderData() is useData().
import type { Load } from "hamur/app"
import { getPost } from "../../../server/index.ts"
export const load = (async ({ params }) => ({ post: await getPost({ id: params.postId as string }) })) satisfies Load
import { Link, useData, useHead } from "@hamur/adapter-react"
export default function Post() {
const { post } = useData<{ post: { id: string; title: string; body: string } }>()
useHead({ title: post.title })
return (
<article>
<h1>{post.title}</h1>
<p>{post.body}</p>
<Link to="/posts">All posts</Link>
</article>
)
}
Search params
validateSearch is the search export of the page, and loaderDeps is searchKeys of its load. The schema is validated before the middleware and the load, on the server and in the browser, and a change of page re-runs only the load that lists it.
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "hamur/server"
type Issue = { message: string; path?: PropertyKey[] }
type Check<T> = (value: unknown) => { value: T } | { issues: Issue[] }
export function schema<T>(
jsonSchema: Record<string, unknown>,
check: Check<T>,
): StandardSchemaV1<unknown, T> & StandardJSONSchemaV1<unknown, T> {
return {
"~standard": {
version: 1,
vendor: "docs",
validate: check,
jsonSchema: { input: () => jsonSchema, output: () => jsonSchema },
},
} as StandardSchemaV1<unknown, T> & StandardJSONSchemaV1<unknown, T>
}
import type { Load } from "hamur/app"
import { listPosts } from "../../../server/index.ts"
export const searchKeys = ["page"]
export const load = (async ({ search }) => ({
page: Number(search.page ?? 1),
posts: await listPosts(),
})) satisfies Load
import { Link, useData, useSearch } from "@hamur/adapter-react"
import { schema } from "../../utils/standard-schema.ts"
export const search = schema<{ page: number }>(
{ type: "object", properties: { page: { type: "integer" } } },
(value) => {
const page = Number((value as { page?: unknown } | undefined)?.page ?? 1)
return Number.isInteger(page) && page >= 1
? { value: { page } }
: { issues: [{ message: "page must be a whole number from 1", path: ["page"] }] }
},
)
export default function Posts() {
const { posts } = useData<{ page: number; posts: { id: string; title: string }[] }>()
const page = useSearch((current) => Number(current.page))
return (
<section>
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link to={`/posts/${post.id}`}>{post.title}</Link>
</li>
))}
</ul>
<button type="button" onClick={() => page.set((prev) => ({ ...prev, page: Number(prev.page) + 1 }))}>
Page {page.value + 1}
</button>
</section>
)
}
Server functions
A server function is a handler. There is no "use server" or compiler split to learn: a handler is a module-level defineHandler export of server/index.ts, and the build writes the browser stub.
| TanStack Start | Hamur | Status | Differences | Docs |
|---|---|---|---|---|
createServerFn({ method: "GET" }) | defineHandler({ method: "GET", handler }) from hamur/server | different | Handlers | |
createServerFn({ method: "POST" }) | defineHandler({ handler }) | different | POST is the default | Handlers |
| the input validator of a server function | input: schema | different | any Standard Schema; 400 Validation failed with data.issues | Handlers |
.handler(async ({ data }) => …) | handler(input, { event }) | different | event is the request | Handlers |
calling fn({ data }) | fn(input) | different | the stub makes a request in the browser and a call in process on the server | Handlers |
useServerFn(fn) | useAction(fn) from @hamur/adapter-react | different | state, failure, error, pending and run(input) | Forms and login |
| a server function in a form | <Form action={fn}> from @hamur/adapter-react | different | works without JavaScript | Forms and login |
redirect() thrown in a server function | return redirect(to) from hamur/app | same | Handlers | |
server routes (server: { handlers } in a route) | defineHandler({ route, raw: true }) | different | one handler per method; it returns a Response | Server |
createMiddleware() | defineMiddleware from hamur/app | different | listed in middleware of a handler or in handlerMiddleware of defineServer; a request middleware is in defineServer({ middleware }) | Handlers |
| the helpers that read the request and set a header | event.request, getRequestHeader(event, …), setHeader(event, …) | different | event is ctx.event | Server |
createServerOnlyFn, createClientOnlyFn | server-only and client-only imports | different | the import guard fails the build on the wrong side | Handlers |
A server route with a raw body, such as a webhook, is a handler with a route:
import { defineHandler } from "hamur/server"
export const webhook = defineHandler({
route: "/api/webhook",
method: "POST",
raw: true,
async handler(_, { event }) {
const body = await event.request.text()
return new Response(`received ${body.length} bytes`, { status: 202 })
},
})
A form posts to a handler and works without JavaScript:
import { Form, useAction } from "@hamur/adapter-react"
import { createPost } from "../../../server/index.ts"
export default function NewPost() {
const { failure } = useAction(createPost)
return (
<Form action={createPost}>
<input name="id" />
<input name="title" />
<button>Create</button>
{failure ? <p role="alert">Check the fields</p> : null}
</Form>
)
}
Middleware and guards
beforeLoad runs before the loader and may throw redirect. Route middleware is the same step: it runs before the page's load, may return redirect(to), and runs on the server for the first request and in the browser for each navigation. In the browser a user can skip it, so it guards no data. Check who asks in the handler, as Sessions and security says.
import { defineRouteMiddleware, redirect } from "hamur/app"
export default defineRouteMiddleware((to, from, ctx) => {
if (!ctx.state.get("user")) return redirect(`/login?next=${encodeURIComponent(to.fullPath)}`)
})
A folder shares a guard through its _meta.ts, which is where a pathless layout route held its beforeLoad:
import type { PageMeta } from "hamur/app"
import auth from "../../middleware/auth.ts"
export const meta = { middleware: [auth], layout: "admin" } satisfies PageMeta
Middleware of the server functions is handler middleware, which wraps validation and the handler:
import { defineMiddleware } from "hamur/app"
import { requireUser } from "../utils/auth.ts"
export const auth = defineMiddleware<{}, { user: string }>({
async server({ event, next }) {
return next({ context: { user: await requireUser(event) } })
},
async client({ next }) {
return next({ sendContext: { locale: navigator.language } })
},
})
Rows with no equivalent yet
The router context and Await with a deferred loader value have no Hamur form today. The rows above say what to write instead.