Skip to content

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

  1. Install Hamur: bun remove @tanstack/react-start @tanstack/react-router, then bun add hamur @hamur/adapter-react.
  2. Write hamur.config.ts with defineConfig({ framework: "react" }). Vite plugins are covered in Vite plugins.
  3. Move each file of src/routes/ to app/pages/, using the tables below. __root.tsx becomes app/app.tsx and a layout.
  4. Split each createFileRoute call into its files: the component stays in the page, loader becomes a load that calls a handler, each createServerFn becomes a handler.
  5. Run hamur dev, open each page, then hamur build.

Route files

{path} is the folders under app/pages/.

TanStack StartHamurStatusDifferencesDocs
src/routes/index.tsxapp/pages/index.tsxsameRouting
posts.$postId.tsx, posts/$postId.tsxapp/pages/posts/[postId].tsxdifferent$param becomes [param], and a dotted name is a folderRouting
$.tsx (a splat)app/pages/[...path].tsxdifferent[...path] never matches an empty path; use [[...path]] for thatRouting
_authed.tsx (a pathless layout route)(authed).tsx beside the folder (authed)/differentthe group adds nothing to the pathRouting
posts.tsx with <Outlet />posts.tsx beside the folder posts/, with OutletsameRouting
__root.tsx and createRootRouteapp/app.tsx, app/layouts/default.tsx and app.head of hamur.config.tsdifferentHamur writes <html>, <head> and <body>Routing
createFileRoute("/posts/$postId")the file pathdifferentthere is no route-id string to keep in sync; hamur typegen types the routeData
routeTree.gen.ts.hamur/differentgenerated by hamur typegen; never editedTypeScript
router.tsx with createRouterapp/router.options.tsdifferentrouter options only; Hamur creates the routerRouting
virtual file routesa route table in codedifferentRouting

Route options

A route is one createFileRoute call with options. In Hamur the options are spread over the files of the route.

TanStack StartHamurStatusDifferencesDocs
componentexport default of the page filesameRouting
loaderload in x.load.ts, calling a handlerdifferentthe server code is the handlerData
Route.useLoaderData()useData() from @hamur/adapter-reactdifferenttype it with useData<T>()Data
Route.useParams()useRoute().paramsdifferenta catch-all param is a string[]Routing
Route.useSearch()useSearch() from @hamur/adapter-reactdifferentreturns { value, set }Routing
validateSearchexport const search, a Standard SchemadifferentZod, Valibot and ArkType schemas work as they are; an invalid query answers 400Routing
loaderDepsexport const searchKeys in the page's x.load.tsdifferentan array of string literals; only those keys re-run the loadData
beforeLoadroute middlewaredifferenta function the page imports and passes in meta.middleware; it steers and guards no dataRouting
context and beforeLoad returning a contextnonenonepass what a page needs through useData(), or read it in a handlerData
head, meta, linksuseHead from @hamur/adapter-react, or head in the page's metadifferentHead
errorComponentx.error.tsx beside the page, or _error.tsx in a folderdifferentit reads the error with useError() and leaves with clearError()Routing
notFoundComponentx.not-found.tsx beside the page, or _not-found.tsxdifferentRouting
pendingComponentx.pending.tsx beside the page, or _pending.tsxdifferentit shows after 1000 ms of a client navigationRouting
staleTime, gcTimemeta.staleTime, meta.gcTimesamethe client data cache of the pageData
ssr: falsemeta.ssrdifferentfalse renders the page in the browser onlyRouting
redirect({ to })redirect(to) from hamur/appsamereturned or thrown; another origin needs { external: true }Routing
notFound()notFound() from hamur/appsameErrors
router.invalidate()useRouter().refresh()differentrefresh(key) re-runs the loads that declared the keyData
useNavigate()useRouter().navigate(to, { replace })differentNavigation
<Link to params search>Link from @hamur/adapter-reactdifferentto is the path; query takes an object or (prev) => nextNavigation
Await and a deferred loader valuenonenonea slow part is a useAsyncData call below the pageData
useRouterState()useRoute() and useNavigation()differentAPI: 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.

ts
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
  },
})
ts
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().

ts
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
tsx
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.

ts
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>
}
ts
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
tsx
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 StartHamurStatusDifferencesDocs
createServerFn({ method: "GET" })defineHandler({ method: "GET", handler }) from hamur/serverdifferentHandlers
createServerFn({ method: "POST" })defineHandler({ handler })differentPOST is the defaultHandlers
the input validator of a server functioninput: schemadifferentany Standard Schema; 400 Validation failed with data.issuesHandlers
.handler(async ({ data }) => …)handler(input, { event })differentevent is the requestHandlers
calling fn({ data })fn(input)differentthe stub makes a request in the browser and a call in process on the serverHandlers
useServerFn(fn)useAction(fn) from @hamur/adapter-reactdifferentstate, failure, error, pending and run(input)Forms and login
a server function in a form<Form action={fn}> from @hamur/adapter-reactdifferentworks without JavaScriptForms and login
redirect() thrown in a server functionreturn redirect(to) from hamur/appsameHandlers
server routes (server: { handlers } in a route)defineHandler({ route, raw: true })differentone handler per method; it returns a ResponseServer
createMiddleware()defineMiddleware from hamur/appdifferentlisted 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 headerevent.request, getRequestHeader(event, …), setHeader(event, …)differentevent is ctx.eventServer
createServerOnlyFn, createClientOnlyFnserver-only and client-only importsdifferentthe import guard fails the build on the wrong sideHandlers

A server route with a raw body, such as a webhook, is a handler with a route:

ts
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:

tsx
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.

ts
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:

ts
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:

ts
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.