# 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](/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](/recipes/tanstack-query).

The shape is one thing in Hamur: a [handler](/handlers), 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](/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 Start                           | Hamur                                                                        | Status    | Differences                                                                  | Docs                                                             |
| ---------------------------------------- | ---------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `src/routes/index.tsx`                   | `app/pages/index.tsx`                                                        | same      |                                                                              | [Routing](/api-reference/routing-details#files-and-routes)       |
| `posts.$postId.tsx`, `posts/$postId.tsx` | `app/pages/posts/[postId].tsx`                                               | different | `$param` becomes `[param]`, and a dotted name is a folder                    | [Routing](/api-reference/routing-details#files-and-routes)       |
| `$.tsx` (a splat)                        | `app/pages/[...path].tsx`                                                    | different | `[...path]` never matches an empty path; use `[[...path]]` for that          | [Routing](/api-reference/routing-details#files-and-routes)       |
| `_authed.tsx` (a pathless layout route)  | `(authed).tsx` beside the folder `(authed)/`                                 | different | the group adds nothing to the path                                           | [Routing](/api-reference/routing-details#pathless-group-layouts) |
| `posts.tsx` with `<Outlet />`            | `posts.tsx` beside the folder `posts/`, with `Outlet`                        | same      |                                                                              | [Routing](/api-reference/routing-details#nested-routes)          |
| `__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](/api-reference/routing-details#root-component)         |
| `createFileRoute("/posts/$postId")`      | the file path                                                                | different | there is no route-id string to keep in sync; `hamur typegen` types the route | [Data](/data#xloadts)                                            |
| `routeTree.gen.ts`                       | `.hamur/`                                                                    | different | generated by `hamur typegen`; never edited                                   | [TypeScript](/typescript)                                        |
| `router.tsx` with `createRouter`         | `app/router.options.ts`                                                      | different | router options only; Hamur creates the router                                | [Routing](/api-reference/navigation-details#router-options)      |
| virtual file routes                      | a route table in code                                                        | different |                                                                              | [Routing](/api-reference/routing-details#a-route-table-in-code)  |

## 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](/api-reference/routing-details#files-and-routes)                          |
| `loader`                                       | `load` in `x.load.ts`, calling a handler                              | different | the server code is the handler                                                            | [Data](/data#xloadts)                                                               |
| `Route.useLoaderData()`                        | `useData()` from `@hamur/adapter-react`                               | different | type it with `useData<T>()`                                                               | [Data](/data#xloadts)                                                               |
| `Route.useParams()`                            | `useRoute().params`                                                   | different | a catch-all param is a `string[]`                                                         | [Routing](/api-reference/routing-details#files-and-routes)                          |
| `Route.useSearch()`                            | `useSearch()` from `@hamur/adapter-react`                             | different | returns `{ value, set }`                                                                  | [Routing](/api-reference/routing-details#search-params)                             |
| `validateSearch`                               | `export const search`, a Standard Schema                              | different | Zod, Valibot and ArkType schemas work as they are; an invalid query answers 400           | [Routing](/api-reference/routing-details#search-params)                             |
| `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](/data#search-keys)                                                           |
| `beforeLoad`                                   | route middleware                                                      | different | a function the page imports and passes in `meta.middleware`; it steers and guards no data | [Routing](/api-reference/routing-details#route-middleware)                          |
| `context` and `beforeLoad` returning a context | none                                                                  | none      | pass what a page needs through `useData()`, or read it in a handler                       | [Data](/data)                                                                       |
| `head`, `meta`, `links`                        | `useHead` from `@hamur/adapter-react`, or `head` in the page's `meta` | different |                                                                                           | [Head](/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](/api-reference/routing-details#route-boundaries-and-not-found-components) |
| `notFoundComponent`                            | `x.not-found.tsx` beside the page, or `_not-found.tsx`                | different |                                                                                           | [Routing](/api-reference/routing-details#route-boundaries-and-not-found-components) |
| `pendingComponent`                             | `x.pending.tsx` beside the page, or `_pending.tsx`                    | different | it shows after 1000 ms of a client navigation                                             | [Routing](/api-reference/routing-details#pending-components)                        |
| `staleTime`, `gcTime`                          | `meta.staleTime`, `meta.gcTime`                                       | same      | the client data cache of the page                                                         | [Data](/data#the-client-data-cache)                                                 |
| `ssr: false`                                   | `meta.ssr`                                                            | different | `false` renders the page in the browser only                                              | [Routing](/api-reference/routing-details#page-meta)                                 |
| `redirect({ to })`                             | `redirect(to)` from `hamur/app`                                       | same      | returned or thrown; another origin needs `{ external: true }`                             | [Routing](/api-reference/routing-details#route-middleware)                          |
| `notFound()`                                   | `notFound()` from `hamur/app`                                         | same      |                                                                                           | [Errors](/errors#status-helpers)                                                    |
| `router.invalidate()`                          | `useRouter().refresh()`                                               | different | `refresh(key)` re-runs the `load`s that declared the key                                  | [Data](/data#reload-the-data)                                                       |
| `useNavigate()`                                | `useRouter().navigate(to, { replace })`                               | different |                                                                                           | [Navigation](/navigation)                                                           |
| `<Link to params search>`                      | `Link` from `@hamur/adapter-react`                                    | different | `to` is the path; `query` takes an object or `(prev) => next`                             | [Navigation](/navigation)                                                           |
| `Await` and a deferred loader value            | none                                                                  | none      | a slow part is a `useAsyncData` call below the page                                       | [Data](/data)                                                                       |
| `useRouterState()`                             | `useRoute()` and `useNavigation()`                                    | different |                                                                                           | [API: adapters](/api-reference/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 [migrate-tanstack/server/posts.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 [migrate-tanstack/server/index.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 [migrate-tanstack/app/pages/posts/[postId].load.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 [migrate-tanstack/app/pages/posts/[postId].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 [migrate-tanstack/app/utils/standard-schema.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 [migrate-tanstack/app/pages/posts/index.load.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 [migrate-tanstack/app/pages/posts/index.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 Start                                     | Hamur                                                                | Status    | Differences                                                                                                                                | Docs                                                     |
| -------------------------------------------------- | -------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- |
| `createServerFn({ method: "GET" })`                | `defineHandler({ method: "GET", handler })` from `hamur/server`      | different |                                                                                                                                            | [Handlers](/handlers#defining-a-handler)                 |
| `createServerFn({ method: "POST" })`               | `defineHandler({ handler })`                                         | different | `POST` is the default                                                                                                                      | [Handlers](/handlers#defining-a-handler)                 |
| the input validator of a server function           | `input: schema`                                                      | different | any Standard Schema; 400 `Validation failed` with `data.issues`                                                                            | [Handlers](/handlers#validation)                         |
| `.handler(async ({ data }) => …)`                  | `handler(input, { event })`                                          | different | `event` is the request                                                                                                                     | [Handlers](/handlers#defining-a-handler)                 |
| calling `fn({ data })`                             | `fn(input)`                                                          | different | the stub makes a request in the browser and a call in process on the server                                                                | [Handlers](/handlers#calling-a-handler)                  |
| `useServerFn(fn)`                                  | `useAction(fn)` from `@hamur/adapter-react`                          | different | `state`, `failure`, `error`, `pending` and `run(input)`                                                                                    | [Forms and login](/forms-and-login)                      |
| a server function in a form                        | `<Form action={fn}>` from `@hamur/adapter-react`                     | different | works without JavaScript                                                                                                                   | [Forms and login](/forms-and-login)                      |
| `redirect()` thrown in a server function           | `return redirect(to)` from `hamur/app`                               | same      |                                                                                                                                            | [Handlers](/handlers#errors-and-redirects-on-the-client) |
| server routes (`server: { handlers }` in a route)  | `defineHandler({ route, raw: true })`                                | different | one handler per method; it returns a `Response`                                                                                            | [Server](/server#a-handler-with-a-route)                 |
| `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](/handlers#middleware)                         |
| the helpers that read the request and set a header | `event.request`, `getRequestHeader(event, …)`, `setHeader(event, …)` | different | `event` is `ctx.event`                                                                                                                     | [Server](/server)                                        |
| `createServerOnlyFn`, `createClientOnlyFn`         | `server-only` and `client-only` imports                              | different | the import guard fails the build on the wrong side                                                                                         | [Handlers](/handlers#import-guards)                      |

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

````ts [migrate-tanstack/server/webhook.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 [migrate-tanstack/app/pages/posts/new.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](/sessions-and-security#protecting-a-page-and-its-data) says.

````ts [auth-middleware.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 [routing/admin/_meta.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 [forms/server/guards/auth.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.
