# Migrating from Fresh

These tables map Fresh (2.x, with Preact) to Hamur: its files, its routing, its handlers and `ctx`, its middleware, its islands, its environment variables and its config. The tables on pages, data and the server in [Migrating from Nuxt](/migrating-from-nuxt) apply to any app. The `Status` column says how close the Hamur way is: `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 Fresh: the move is by hand, route by route, with the tables below. Hamur runs on Bun, Node, Workers and static hosting, not on Deno ([Deploy](/deploy)), so `deno.json`, `jsr:` imports and `deno task` become `package.json`, npm packages and `bun run`. Keep `preact`; the adapter is `@hamur/adapter-preact`.

The shape is one thing in Hamur: a [handler](/handlers), a typed function that runs on the server, exported from `server/index.ts`. A Fresh route file mixes a handler and a component; in Hamur a page, its `load` and the handler are three files. The `load` calls the handler where a Fresh `GET` handler called `ctx.render(data)`, and a form posts to a handler where a `POST` handler read the form. A handler is a public endpoint that must check who calls it.

## Step by step

1. Install Hamur: `bun add hamur @hamur/adapter-preact preact`, and remove `deno.json` once nothing reads it.
2. Write `hamur.config.ts` with `defineConfig({ framework: "preact" })` from `fresh.config.ts` and `main.ts` ([config keys](#config-keys)).
3. Move `routes/` to `app/pages/`, `components/` to `app/components/`, `islands/` to `app/islands/` and `static/` to `public/` ([Files and folders](#files-and-folders)).
4. Split each route file: the component stays in the page, a `GET` handler becomes a `load` that calls a handler, and each other handler becomes a handler of `server/` ([Handlers and `ctx`](#handlers-and-ctx)).
5. Move `_middleware.ts` files to the `middleware` list of `defineServer` ([Middleware](#middleware)).
6. Run `hamur dev`, open each page, then `hamur build`.

## Files and folders

| Fresh                                       | Hamur                                          | Status    | Differences                                                                                                                                                                                                     |
| ------------------------------------------- | ---------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deno.json`                                 | `package.json` and `tsconfig.json`             | different | npm packages, `bun install`, `bun run`                                                                                                                                                                          |
| `main.ts`, `new App()`                      | `hamur.config.ts` and `server/index.ts`        | different | the app is built from the folders; `defineServer` holds middleware and plugins                                                                                                                                  |
| `dev.ts`, `deno task dev`                   | `hamur dev`                                    | different | see [Dev server](/dev-server)                                                                                                                                                                                   |
| `fresh.config.ts`                           | `hamur.config.ts`                              | different | with `defineConfig` of `hamur` and `framework: "preact"`; the keys are [below](#config-keys)                                                                                                                    |
| `client.ts`                                 | an app plugin                                  | different | `app/plugins/*.client.ts` runs when the app starts in the browser. See [Plugins and hooks](/plugins-and-hooks#app-plugins)                                                                                      |
| `routes/**`                                 | `app/pages/**`                                 | different | one file per route, without the handler; see [Routing, heading by heading](#routing-heading-by-heading)                                                                                                         |
| `routes/api/**`                             | handlers with a `route`, in `server/`          | different | see [Handlers and `ctx`](#handlers-and-ctx)                                                                                                                                                                     |
| `routes/_app.tsx`                           | `app/app.tsx`                                  | different | the root renders `Outlet`; Hamur writes `<html>`, `<head>` and `<body>`. See [Root component](/api-reference/routing-details#root-component)                                                                    |
| `routes/_layout.tsx`                        | `app/layouts/default.tsx`                      | different | a layout renders `children`; a folder's layout is its parent page. See [Layouts](/api-reference/routing-details#layouts)                                                                                        |
| `routes/_middleware.ts`                     | `middleware` of `defineServer`                 | different | see [Middleware](#middleware)                                                                                                                                                                                   |
| `routes/_error.tsx`, `_404.tsx`, `_500.tsx` | `app/error.tsx` and `app/pages/_not-found.tsx` | different | see [The error page](/errors#the-error-page)                                                                                                                                                                    |
| `components/**`                             | `app/components/**`                            | same      | import a component by its path. See [Co-located components](/api-reference/routing-details#co-located-components)                                                                                               |
| `islands/**`                                | `app/islands/**`                               | different | an island is rendered through `Island`; see [Islands](#islands)                                                                                                                                                 |
| `static/`                                   | `public/`                                      | different | copied into the build as it is. See [Directory structure](/directory-structure)                                                                                                                                 |
| `_fresh/`                                   | `.output/`                                     | different | generated; keep it in `.gitignore`                                                                                                                                                                              |
| `utils.ts` with `createDefine<State>()`     | none                                           | none      | `define.page`, `define.handlers` and `define.middleware` have no counterpart: `defineHandler`, `defineMiddleware` and a page's `export default` are typed on their own. Type the state with `HamurEventContext` |

## Routing, heading by heading

Each heading of the Fresh routing page has a row, in its order. `{path}` is the folders under `app/pages/`.

| Fresh                                          | Hamur                                                      | Status    | Differences                                                                                                                                 |
| ---------------------------------------------- | ---------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| file-system routes: `app.fsRoutes()`           | `app/pages/`                                               | different | there is nothing to call; every file under `app/pages/` is a route. See [Files and routes](/api-reference/routing-details#files-and-routes) |
| `routes/index.tsx`                             | `app/pages/index.tsx`                                      | same      |                                                                                                                                             |
| `routes/about.tsx`                             | `app/pages/about.tsx`                                      | same      |                                                                                                                                             |
| `routes/blog/index.tsx`                        | `app/pages/blog/index.tsx`                                 | same      |                                                                                                                                             |
| dynamic routes: `routes/blog/[slug].tsx`       | `app/pages/blog/[slug].tsx`                                | same      | `ctx.params.slug` is `useRoute().params.slug`                                                                                               |
| catch-all routes: `routes/files/[...path].tsx` | `app/pages/files/[...path].tsx`                            | different | the param is a `string[]`, and `[...path]` never matches an empty path; `[[...path]]` does                                                  |
| route groups: `routes/(auth)/login.tsx`        | `app/pages/(auth)/login.tsx`                               | same      | a group adds nothing to the path. See [Pathless group layouts](/api-reference/routing-details#pathless-group-layouts)                       |
| a group's own `_layout.tsx`                    | `app/pages/(auth).tsx` beside the folder                   | different | it renders `Outlet`                                                                                                                         |
| programmatic routes: `app.get("/x", handler)`  | `defineHandler({ route: "/x", method: "GET", raw: true })` | different | exported from `server/index.ts`. See [A handler with a route](/server#a-handler-with-a-route)                                               |
| `app.post`, `app.all`                          | `defineHandler({ route, method, raw: true })`              | different | one handler for each method; there is no `all`                                                                                              |
| `export const config = { routeOverride }`      | `meta.path`                                                | different | a literal in `export const meta`; `:id` for a param. See [Page meta](/api-reference/routing-details#page-meta)                              |
| `config.skipAppWrapper`                        | `meta.appRoot: false`                                      | different | the page renders without `app/app.tsx`                                                                                                      |
| `config.skipInheritedLayouts`                  | `meta.layout: false`                                       | different | or `meta.parents: false` for the parent pages                                                                                               |
| `config.csp`                                   | `server.csp`                                               | different | one key for the app; see [Sessions and security](/sessions-and-security)                                                                    |
| the 404 page: `_404.tsx`                       | `app/pages/[...slug].tsx`, or `app/pages/_not-found.tsx`   | different | it answers 200 unless the page throws `createError({ status: 404 })`; see [A URL no page matches](/errors#a-url-no-page-matches)            |
| `ctx.render()` in a route                      | the page's default export                                  | different | the data comes from the page's `load`; see [Handlers and `ctx`](#handlers-and-ctx)                                                          |

## Handlers and `ctx`

A route file with `export const handler = define.handlers({ GET(ctx) { return page({ post }) } })` and a component that reads `props.data` becomes three files: a handler, a `load` that calls it, and a page that reads the data with `useData()`.

````ts [migrate-fresh/server/posts.ts]
import { redirect } from "hamur/app"
import { createError, defineHandler } from "hamur/server"
import { schema } from "../../migrate-next/server/schema.ts"

const posts = new Map([["hello", { slug: "hello", title: "Hello" }]])

const slugInput = schema<{ slug: string }>(
  { type: "object", properties: { slug: { type: "string" } }, required: ["slug"] },
  (value) => {
    const slug = (value as { slug?: unknown } | undefined)?.slug
    return typeof slug === "string" && slug
      ? { value: { slug } }
      : { issues: [{ message: "A slug is required", path: ["slug"] }] }
  },
)

export const getPost = defineHandler({
  method: "GET",
  input: slugInput,
  handler({ slug }) {
    const post = posts.get(slug)
    if (!post) throw createError({ status: 404, message: "Post not found" })
    return post
  },
})

export const removePost = defineHandler({
  input: slugInput,
  handler({ slug }, { event }) {
    if (!event.context.user) throw createError({ status: 401, message: "Log in first" })
    posts.delete(slug)
    return redirect("/posts")
  },
})

export const feed = defineHandler({
  route: "/api/feed",
  method: "GET",
  raw: true,
  handler: () => Response.json([...posts.values()]),
})
````

````ts [migrate-fresh/server/index.ts]
import { defineServer } from "hamur/server"
import { admin, session, timing } from "./middleware.ts"

export { feed, getPost, removePost } from "./posts.ts"

export default defineServer({
  middleware: [timing, session, { route: "/admin/**", handler: admin }],
})
````

````ts [migrate-fresh/app/pages/posts/[slug].load.ts]
import type { Load } from "hamur/app"
import { getPost } from "../../../server/index.ts"

export const load = (async ({ params }) => ({ post: await getPost({ slug: params.slug as string }) })) satisfies Load
````

| Fresh                                  | Hamur                                                      | Status    | Differences                                                                                                                                        |
| -------------------------------------- | ---------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `define.handlers({ GET })` for a page  | `load` in `x.load.ts`, calling a `GET` handler             | different | the handler is the server code. See [`x.load.ts`](/data#xloadts)                                                                                   |
| `page(data)`, `ctx.render(data)`       | the return value of `load`                                 | different | the page reads it with `useData()` from `@hamur/adapter-preact`. See [Data](/data)                                                                 |
| `props.data` of a page                 | `useData()` from `@hamur/adapter-preact`                   | different | type it with `useData<T>()`                                                                                                                        |
| `define.handlers({ POST })` for a form | `defineHandler({ input, handler })`                        | different | a `POST`; the form is decoded before the handler. See [Forms](/handlers#forms)                                                                     |
| `<form method="POST">`                 | `<Form action={fn}>` from `@hamur/adapter-preact`          | different | works without JavaScript. See [Forms and login](/forms-and-login)                                                                                  |
| `await ctx.req.formData()`             | the `input` of the handler                                 | different | with `raw: true` and a `route`, `await event.request.formData()`                                                                                   |
| `ctx.req`                              | `event.request`                                            | different | `event` is the second argument of a handler: `handler(input, { event })`                                                                           |
| `ctx.url`                              | `event.url`                                                | same      |                                                                                                                                                    |
| `ctx.params`                           | `event.params` in a handler, `params` in a `load`          | same      |                                                                                                                                                    |
| `ctx.state`                            | `event.context`                                            | different | a middleware writes `event.context.user`; a handler reads it, and a `load` reads it as `ctx.event.context`. Type the keys with `HamurEventContext` |
| `ctx.redirect("/x", 303)`              | `redirect("/x", 303)` from `hamur/app`                     | same      | return or throw it from a `load`, a middleware or a handler                                                                                        |
| `ctx.next()`                           | `await next()`                                             | same      | see [Middleware](#middleware)                                                                                                                      |
| `ctx.info.remoteAddr`                  | `getRequestIP(event)` of `hamur/server`                    | different |                                                                                                                                                    |
| `ctx.config`, `ctx.route`              | `useRuntimeConfig()`, `useRoute()`                         | different | `useRuntimeConfig` from `hamur/server` in a handler                                                                                                |
| `ctx.isPartial`                        | none                                                       | none      | see [Islands](#islands)                                                                                                                            |
| `new Response(JSON.stringify(x))`      | `Response.json(x)`, or a plain return value                | different | a handler returns a value, which Hamur serializes                                                                                                  |
| `throw new HttpError(404)`             | `throw createError({ status: 404 })` from `hamur/server`   | different | `notFound()` from `hamur/app` in a `load`. See [Status helpers](/errors#status-helpers)                                                            |
| cookies of `@std/http`                 | `getCookie`, `setCookie`, `deleteCookie` of `hamur/server` | different | each takes the `event`                                                                                                                             |

## Middleware

A `_middleware.ts` file covers its folder and the folders below it. `defineServer` has one list, and an entry with a `route` covers a folder the same way. `ctx.state` is `event.context`, and `ctx.next()` is `await next()`.

````ts [migrate-fresh/server/middleware.ts]
import { redirect } from "hamur/app"
import { defineMiddleware, getCookie } from "hamur/server"

export const session = defineMiddleware(({ event }) => {
  event.context.user = getCookie(event, "session") ?? null
})

export const admin = defineMiddleware(({ event }) => {
  if (!event.context.user) throw redirect("/login")
})

export const timing = defineMiddleware(async ({ event, next }) => {
  const started = performance.now()
  const answer = await next()
  event.response.headers.set("server-timing", `total;dur=${Math.round(performance.now() - started)}`)
  return answer
})
````

| Fresh                                     | Hamur                                                             | Status    | Differences                                                                                                                |
| ----------------------------------------- | ----------------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------- |
| `routes/_middleware.ts`                   | a step of `middleware` in `defineServer`                          | different | `defineMiddleware(({ event, next }) => …)` from `hamur/server`. See [Middleware](/server#middleware)                       |
| `routes/admin/_middleware.ts`             | `{ route: "/admin/**", handler }`                                 | different | there is no `matcher`; the pattern is a route rule's, and `/admin/**` also matches `/admin`                                |
| `app.use(mw)`                             | `middleware: [mw]`                                                | same      | outermost first                                                                                                            |
| `ctx.state.user = …`                      | `event.context.user = …`                                          | different | see [Handlers and `ctx`](#handlers-and-ctx)                                                                                |
| `return await ctx.next()`                 | `return next()`, or return nothing                                | different | code after `await next()` sees the answer and may set `event.response.headers`                                             |
| `return ctx.redirect("/login")`           | `throw redirect("/login")` from `hamur/app`                       | different | a thrown or returned `redirect()` redirects                                                                                |
| a middleware that guards a `POST` handler | `handlerMiddleware`, or `middleware` of the handler               | different | a request step guards the document; the handler's list guards every call. See [Handlers: middleware](/handlers#middleware) |
| `define.middleware(fn)`                   | `defineMiddleware(fn)`                                            | different |                                                                                                                            |
| a guard that steers a navigation          | route middleware the page imports and passes in `meta.middleware` | different | it steers and guards no data. See [Route middleware](/api-reference/routing-details#route-middleware)                      |

## Islands

A Fresh route renders to HTML and hydrates only the components of `islands/`. A Hamur page hydrates whole by default. To keep the Fresh shape, a page sets `meta.hydrate: "islands"` (it needs `experimental.islands: true`), and the components of `app/islands/` are rendered through `Island`. See [Islands](/islands-and-streaming#islands).

| Fresh                                        | Hamur                                                                            | Status    | Differences                                                                                                              |
| -------------------------------------------- | -------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------ |
| a component of `islands/` used in a page     | `Island` from `@hamur/adapter-preact` with a component of `app/islands/`         | different | `<Island component={Counter} props={{ start: 3 }} />`; props are serialized, and a function prop fails the render        |
| an island that hydrates when the page loads  | `on="load"` of `Island`                                                          | same      | `"load"` is the default                                                                                                  |
| an island of `components/`                   | a component of `app/components/`                                                 | different | it hydrates with the page, or renders on the server only on an island page                                               |
| children of an island                        | `children` of `Island`                                                           | different | rendered on the server only and never hydrated                                                                           |
| `IS_BROWSER` from `fresh/runtime`            | `import.meta.client`                                                             | same      | a constant of the build. See [Environment](/environment)                                                                 |
| `useSignal`, `signal` of `@preact/signals`   | the same                                                                         | same      | the signals package works with the Preact adapter; shared state across islands is `useState("key", init)`                |
| Partials: `<Partial>`, `f-client-nav`        | none on a hydrated page; `data-hamur-swap` and `hamur-partial` on an island page | different | a hydrated page navigates in the browser by default. See [Swaps and partials](/islands-and-streaming#swaps-and-partials) |
| `<Head>` of `fresh/runtime`                  | `useHead` from `@hamur/adapter-preact`                                           | different | see [Head](/head)                                                                                                        |
| `asset("/x.css")`                            | an import with `?url`                                                            | different | Hamur hashes the file. See [Directory structure](/directory-structure#assets)                                            |
| `<Fragment>` and `jsx` pragma of `deno.json` | `tsconfig.json`                                                                  | different | Hamur's adapter sets the Preact JSX settings                                                                             |

## Environment variables

| Fresh                               | Hamur                                          | Status    | Differences                                                                                   |
| ----------------------------------- | ---------------------------------------------- | --------- | --------------------------------------------------------------------------------------------- |
| `Deno.env.get("API_KEY")`           | `import { API_KEY } from "#hamur/env/private"` | different | an entry of `defineEnv` in `app/env.ts`; typed, validated at start, never sent to the browser |
| a value the browser needs           | `import { GA_ID } from "#hamur/env/public"`    | different | the entry has `public: true`. See [Environment](/environment)                                 |
| `.env` loaded by `@std/dotenv/load` | `.env`, `.env.local`, `.env.<mode>`            | different | Hamur reads them itself; see [Modes](/environment#modes)                                      |

## Config keys

| Fresh                        | Hamur                                        | Status    | Differences                                                                                |
| ---------------------------- | -------------------------------------------- | --------- | ------------------------------------------------------------------------------------------ |
| `basePath`                   | `app.baseURL`                                | different | it ends with `/`                                                                           |
| `staticDir`                  | `public/`                                    | different | the folder is fixed                                                                        |
| `build.outDir`               | `.output/`                                   | different | the folder is fixed                                                                        |
| `plugins`                    | `modules`                                    | different | see [Modules](/modules)                                                                    |
| `app.listen()`, `Deno.serve` | `hamur build`, then the output of the preset | different | `bun .output/server/index.mjs` on the `bun` preset. See [Deploy](/deploy)                  |
| `build.target`               | `preset`                                     | different | the build target is a preset: `bun`, `node`, `cloudflare`, `vercel`, `netlify` or `static` |

## What Hamur lacks

- Deno: there is no Deno runtime, `deno.json`, `jsr:` import or `Deno.*` API. See [Deploy](/deploy).
- `createDefine`, `define.page`, `define.handlers` and `define.middleware`: the typed helpers are `defineHandler`, `defineMiddleware` and `satisfies Load`.
- `app.all` and a method-less route: write a handler for each method.
- Partials on a hydrated page: the navigator replaces them.
- A route file that holds its handler and its component together: the page, its `load` and the handler are separate files, so the build can drop the server code from the browser bundle.
