Skip to content

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 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), 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, 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).
  3. Move routes/ to app/pages/, components/ to app/components/, islands/ to app/islands/ and static/ to public/ (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).
  5. Move _middleware.ts files to the middleware list of defineServer (Middleware).
  6. Run hamur dev, open each page, then hamur build.

Files and folders

FreshHamurStatusDifferences
deno.jsonpackage.json and tsconfig.jsondifferentnpm packages, bun install, bun run
main.ts, new App()hamur.config.ts and server/index.tsdifferentthe app is built from the folders; defineServer holds middleware and plugins
dev.ts, deno task devhamur devdifferentsee Dev server
fresh.config.tshamur.config.tsdifferentwith defineConfig of hamur and framework: "preact"; the keys are below
client.tsan app plugindifferentapp/plugins/*.client.ts runs when the app starts in the browser. See Plugins and hooks
routes/**app/pages/**differentone file per route, without the handler; see Routing, heading by heading
routes/api/**handlers with a route, in server/differentsee Handlers and ctx
routes/_app.tsxapp/app.tsxdifferentthe root renders Outlet; Hamur writes <html>, <head> and <body>. See Root component
routes/_layout.tsxapp/layouts/default.tsxdifferenta layout renders children; a folder's layout is its parent page. See Layouts
routes/_middleware.tsmiddleware of defineServerdifferentsee Middleware
routes/_error.tsx, _404.tsx, _500.tsxapp/error.tsx and app/pages/_not-found.tsxdifferentsee The error page
components/**app/components/**sameimport a component by its path. See Co-located components
islands/**app/islands/**differentan island is rendered through Island; see Islands
static/public/differentcopied into the build as it is. See Directory structure
_fresh/.output/differentgenerated; keep it in .gitignore
utils.ts with createDefine<State>()nonenonedefine.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/.

FreshHamurStatusDifferences
file-system routes: app.fsRoutes()app/pages/differentthere is nothing to call; every file under app/pages/ is a route. See Files and routes
routes/index.tsxapp/pages/index.tsxsame
routes/about.tsxapp/pages/about.tsxsame
routes/blog/index.tsxapp/pages/blog/index.tsxsame
dynamic routes: routes/blog/[slug].tsxapp/pages/blog/[slug].tsxsamectx.params.slug is useRoute().params.slug
catch-all routes: routes/files/[...path].tsxapp/pages/files/[...path].tsxdifferentthe param is a string[], and [...path] never matches an empty path; [[...path]] does
route groups: routes/(auth)/login.tsxapp/pages/(auth)/login.tsxsamea group adds nothing to the path. See Pathless group layouts
a group's own _layout.tsxapp/pages/(auth).tsx beside the folderdifferentit renders Outlet
programmatic routes: app.get("/x", handler)defineHandler({ route: "/x", method: "GET", raw: true })differentexported from server/index.ts. See A handler with a route
app.post, app.alldefineHandler({ route, method, raw: true })differentone handler for each method; there is no all
export const config = { routeOverride }meta.pathdifferenta literal in export const meta; :id for a param. See Page meta
config.skipAppWrappermeta.appRoot: falsedifferentthe page renders without app/app.tsx
config.skipInheritedLayoutsmeta.layout: falsedifferentor meta.parents: false for the parent pages
config.cspserver.cspdifferentone key for the app; see Sessions and security
the 404 page: _404.tsxapp/pages/[...slug].tsx, or app/pages/_not-found.tsxdifferentit answers 200 unless the page throws createError({ status: 404 }); see A URL no page matches
ctx.render() in a routethe page's default exportdifferentthe data comes from the page's load; see 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
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
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
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
FreshHamurStatusDifferences
define.handlers({ GET }) for a pageload in x.load.ts, calling a GET handlerdifferentthe handler is the server code. See x.load.ts
page(data), ctx.render(data)the return value of loaddifferentthe page reads it with useData() from @hamur/adapter-preact. See Data
props.data of a pageuseData() from @hamur/adapter-preactdifferenttype it with useData<T>()
define.handlers({ POST }) for a formdefineHandler({ input, handler })differenta POST; the form is decoded before the handler. See Forms
<form method="POST"><Form action={fn}> from @hamur/adapter-preactdifferentworks without JavaScript. See Forms and login
await ctx.req.formData()the input of the handlerdifferentwith raw: true and a route, await event.request.formData()
ctx.reqevent.requestdifferentevent is the second argument of a handler: handler(input, { event })
ctx.urlevent.urlsame
ctx.paramsevent.params in a handler, params in a loadsame
ctx.stateevent.contextdifferenta 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/appsamereturn or throw it from a load, a middleware or a handler
ctx.next()await next()samesee Middleware
ctx.info.remoteAddrgetRequestIP(event) of hamur/serverdifferent
ctx.config, ctx.routeuseRuntimeConfig(), useRoute()differentuseRuntimeConfig from hamur/server in a handler
ctx.isPartialnonenonesee Islands
new Response(JSON.stringify(x))Response.json(x), or a plain return valuedifferenta handler returns a value, which Hamur serializes
throw new HttpError(404)throw createError({ status: 404 }) from hamur/serverdifferentnotFound() from hamur/app in a load. See Status helpers
cookies of @std/httpgetCookie, setCookie, deleteCookie of hamur/serverdifferenteach 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
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
})
FreshHamurStatusDifferences
routes/_middleware.tsa step of middleware in defineServerdifferentdefineMiddleware(({ event, next }) => …) from hamur/server. See Middleware
routes/admin/_middleware.ts{ route: "/admin/**", handler }differentthere is no matcher; the pattern is a route rule's, and /admin/** also matches /admin
app.use(mw)middleware: [mw]sameoutermost first
ctx.state.user = …event.context.user = …differentsee Handlers and ctx
return await ctx.next()return next(), or return nothingdifferentcode after await next() sees the answer and may set event.response.headers
return ctx.redirect("/login")throw redirect("/login") from hamur/appdifferenta thrown or returned redirect() redirects
a middleware that guards a POST handlerhandlerMiddleware, or middleware of the handlerdifferenta request step guards the document; the handler's list guards every call. See Handlers: middleware
define.middleware(fn)defineMiddleware(fn)different
a guard that steers a navigationroute middleware the page imports and passes in meta.middlewaredifferentit steers and guards no data. See 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.

FreshHamurStatusDifferences
a component of islands/ used in a pageIsland 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 loadson="load" of Islandsame"load" is the default
an island of components/a component of app/components/differentit hydrates with the page, or renders on the server only on an island page
children of an islandchildren of Islanddifferentrendered on the server only and never hydrated
IS_BROWSER from fresh/runtimeimport.meta.clientsamea constant of the build. See Environment
useSignal, signal of @preact/signalsthe samesamethe signals package works with the Preact adapter; shared state across islands is useState("key", init)
Partials: <Partial>, f-client-navnone on a hydrated page; data-hamur-swap and hamur-partial on an island pagedifferenta hydrated page navigates in the browser by default. See Swaps and partials
<Head> of fresh/runtimeuseHead from @hamur/adapter-preactdifferentsee Head
asset("/x.css")an import with ?urldifferentHamur hashes the file. See Directory structure
<Fragment> and jsx pragma of deno.jsontsconfig.jsondifferentHamur's adapter sets the Preact JSX settings

Environment variables

FreshHamurStatusDifferences
Deno.env.get("API_KEY")import { API_KEY } from "#hamur/env/private"differentan entry of defineEnv in app/env.ts; typed, validated at start, never sent to the browser
a value the browser needsimport { GA_ID } from "#hamur/env/public"differentthe entry has public: true. See Environment
.env loaded by @std/dotenv/load.env, .env.local, .env.<mode>differentHamur reads them itself; see Modes

Config keys

FreshHamurStatusDifferences
basePathapp.baseURLdifferentit ends with /
staticDirpublic/differentthe folder is fixed
build.outDir.output/differentthe folder is fixed
pluginsmodulesdifferentsee Modules
app.listen(), Deno.servehamur build, then the output of the presetdifferentbun .output/server/index.mjs on the bun preset. See Deploy
build.targetpresetdifferentthe 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.
  • 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.