# Migrating from Next.js This guide maps a Next.js App Router app to Nowaki. It was written from a port that exists in this repository: the comparison blog in [benchmarks/compare](../benchmarks/compare/README.md), which is generated in a Next.js 16 version and a Nowaki version that implement the same pages, islands, form and API route. The snippets marked with a path come from those two apps. They are generated by `node benchmarks/compare/gen.mjs next|nowaki --mode server` from [lib/templates.mjs](../benchmarks/compare/lib/templates.mjs) and [lib/features-fw.mjs](../benchmarks/compare/lib/features-fw.mjs), into `benchmarks/compare/apps/next/` and `benchmarks/compare/apps/nowaki/`. The Nowaki twin builds, serves, posts its form and prerenders with Nowaki 0.20.0. Where the port doesn't cover a feature (route groups, intercepting routes, revalidation, redirects, i18n), the Nowaki side comes from `examples/gallery` and `examples/hello` or from the `.d.ts` files of `@nowaki-dev/runtime`. The short version: the page tree moves from `app/` to `routes/` almost file for file, data fetching moves from async server components into a `loader`, client components move to `islands/` and switch from React to Preact, Server Actions become a page `action` or a `"use server"` module, and `next.config` becomes `nowaki.config.mjs`. ## What changes in the model - **Nothing ships to the browser unless it is an island.** In Next.js every client component and React itself are sent and hydrated. In Nowaki a page is server HTML, and only the components in `islands/` ship JavaScript. On the comparison blog at 10 posts, `/` ships 8.79 KB of JS (gzip) in Nowaki: the islands runtime, the theme toggle and one counter. - **Preact, not React.** Islands are Preact components. `react`, `react-dom` and `react/jsx-runtime` are aliased to `preact/compat`, so many React libraries work, but not all (see [What has no equivalent](#what-has-no-equivalent)). - **Data comes from a `loader`.** Pages are synchronous components that receive `data`; the loader is server-only code that runs before the render. - **One server.** `nowaki start` is a Rust front that serves assets and the ISR cache and runs rendering in a Node process. The deploy adapters (`node`, `bun`, `deno`, `cloudflare`, `vercel`, `static`) produce the same app for other hosts. ## 1. Set up 1. Replace Next.js and React with Nowaki and Preact: ```sh npm remove next react react-dom @types/react eslint-config-next npm install @nowaki-dev/runtime preact preact-render-to-string npm install -D nowaki ``` 2. Copy `tsconfig.json`, `nowaki-env.d.ts` and `nowaki-jsx.d.ts` from a new app (`npm create nowaki@latest`), and delete `next-env.d.ts`. The compare app's `tsconfig.json` had `"jsx": "react-jsx"` and the `next` plugin; Nowaki's uses Preact's JSX. 3. Scripts: ```json { "scripts": { "dev": "nowaki dev", "build": "nowaki build", "start": "nowaki start", "prerender": "nowaki prerender" } } ``` 4. Add explicit extensions to relative imports. Next.js resolves `"../components/Search"`; Nowaki's server build runs as plain ESM and needs `"../islands/Search.tsx"`. ## 2. Files | Next.js (`app/`) | Nowaki | |---|---| | `app/page.tsx` | `routes/index.tsx` | | `app/posts/page.tsx` | `routes/posts/index.tsx` | | `app/posts/[slug]/page.tsx` | `routes/posts/[slug].tsx` | | `app/docs/[...slug]/page.tsx` | `routes/docs/[...slug].tsx` (`params.slug` is an array) | | `app/docs/[[...slug]]/page.tsx` | `routes/docs/index.tsx` and `routes/docs/[...slug].tsx` | | `app/layout.tsx` | `routes/_layout.tsx` (no `` / ``: see [Layouts](#3-layouts)) | | `app/posts/layout.tsx` | `routes/posts/_layout.tsx` | | `app/(marketing)/about/page.tsx` | `routes/(marketing)/about.tsx` (same route group syntax) | | `app/@modal/(.)photo/[id]/page.tsx` | `routes/@modal/(.)photo/[id].tsx` (same parallel and intercepting syntax) | | `app/@modal/default.tsx` | `routes/@modal/default.tsx` | | `app/not-found.tsx` | `routes/_404.tsx` | | `app/global-error.tsx` | `routes/_500.tsx` (server errors) | | `app/loading.tsx` | `routes/loading.tsx` (client navigations only, see below) | | `app/error.tsx` | `routes/error.tsx` (client navigations only, see below) | | `app/api/search/route.ts` | `routes/api/search.ts` | | `app/feed.xml/route.ts` | `routes/feed.xml.ts` (a file route; the extension sets the content type) | | `app/opengraph-image.tsx` | a file route such as `routes/og/[card].png.ts` | | `app/sitemap.ts`, `app/robots.ts` | generated when `site` is set; or `routes/sitemap.xml.ts` | | `middleware.ts` | `routes/_middleware.ts` (one per directory) | | `components/*` with `"use client"` | `islands/*` | | `components/*` (server components) | `components/*` | | `public/` | `public/` | | `next.config.mjs` | `nowaki.config.mjs` | | `.env`, `.env.local` | `.env`, `.env.local` | `loading.tsx` and `error.tsx` differ in when they show. In Next.js `loading.tsx` is a Suspense boundary that also streams on the first load. In Nowaki both are client-router boundaries: the loading UI shows when a client navigation takes over 150 ms, and the error UI when it fails. On a first load, a server error renders `_500`. The error component marks the message element `data-nowaki-error` and the retry button `data-nowaki-reset`; there is no `reset` callback to call from server HTML. ## 3. Layouts The root layout doesn't render `` and ``: Nowaki writes the document, and the layout's attributes go in exports. CSS imports work the same way: a stylesheet imported by a layout, a page, or a component they use is linked on the page. ```tsx // benchmarks/compare/apps/next/app/layout.tsx import "./globals.css"; import ThemeToggle from "../components/ThemeToggle"; export default function RootLayout({ children }: { children: React.ReactNode }) { return (
{children}
); } ``` ```tsx // benchmarks/compare/apps/nowaki/routes/_layout.tsx import "../styles/global.css"; import ThemeToggle from "../islands/ThemeToggle.tsx"; export default function RootLayout({ children }: { children: unknown }) { return (
{children}
); } ``` For `` and other attributes, export them from the layout or a page: ```tsx export const lang = "en"; export const htmlAttrs = { "data-theme": "light" }; export const bodyAttrs = { class: "site" }; ``` Preact accepts `class`, `for` and string `style` as in HTML; `className`, `htmlFor` and style objects work too. Nested layouts receive `children`, and a layout next to `@slot` directories also receives `slots` (`slots.modal`) instead of Next.js's named props. ## 4. Pages and data Next.js reads data in an async server component. Nowaki reads it in a `loader` and passes the result to the page as `data`. The page itself is synchronous. ```tsx // benchmarks/compare/apps/next/app/page.tsx (server mode) import Link from "next/link"; import Island01 from "../components/Island01"; import { posts } from "../lib/posts"; export const metadata = { title: "Home — Next" }; export const dynamic = "force-dynamic"; export default function Home() { const latest = posts.slice(0, 10); return (

A blog

); } ``` ```tsx // benchmarks/compare/apps/nowaki/routes/index.tsx import Island01 from "../islands/Island01.tsx"; import { posts, type Post } from "../lib/posts.ts"; export const title = "Home — Nowaki"; export const loader = () => ({ latest: posts.slice(0, 10) }); export default function Home({ data }: { data: { latest: Post[] } }) { return (

A blog

); } ``` `PageProps` from `@nowaki-dev/runtime` infers `data` from the loader, so the inline type above can go: ```tsx import type { LoaderContext, PageProps } from "@nowaki-dev/runtime"; export const loader = ({ params }: LoaderContext) => ({ post: findPost(String(params.slug)) }); export default function Post({ data }: PageProps) { /* ... */ } ``` | Next.js | Nowaki | |---|---| | `async function Page({ params })` with `await params` | `loader(ctx)` with `ctx.params` (not a promise) | | `searchParams` prop | `ctx.url.searchParams` in the loader, or the `url` prop | | `cookies()`, `headers()` from `next/headers` | `ctx.cookies`, `ctx.headers`, `ctx.get(name)`; `getContext()` in server functions | | `cookies().set(...)` | `ctx.setCookie(name, value, opts)` | | `redirect("/x")` from `next/navigation` | `return ctx.redirect("/x")` (302; pass a status for others) | | `permanentRedirect("/x")` | `return ctx.redirect("/x", 308)` | | `notFound()` | `ctx.status(404)` in the loader, and render the not-found UI in the page | | `export const dynamic = "force-dynamic"` | the default: pages render per request | | `export const dynamic = "force-static"` | `export const revalidate`, or prerender with `staticPaths` | A post that doesn't exist: in Next.js `notFound()` renders `not-found.tsx` with status 404. The compare twin renders "Not found" with status 200; set the status in the loader so it matches: ```tsx // routes/posts/[slug].tsx export const loader = (ctx: LoaderContext) => { const post = posts.find((p) => p.slug === ctx.params.slug); if (!post) { ctx.status(404); return { post: null, html: "" }; } return { post, html: marked.parse(post.body, { async: false }) as string }; }; ``` A loader in a `_layout` passes `data` to that layout. Middleware can pass values to loaders in `ctx.state`. ## 5. Static paths, ISR and revalidation `generateStaticParams` becomes `staticPaths`. It is read by `nowaki prerender` and the static adapter; a server build renders any param on request. ```tsx // benchmarks/compare/apps/next/app/posts/[slug]/page.tsx (static mode) export const dynamicParams = false; export function generateStaticParams() { return posts.map((p) => ({ slug: p.slug })); } ``` ```tsx // benchmarks/compare/apps/nowaki/routes/posts/[slug].tsx export const staticPaths = () => posts.map((p) => ({ slug: p.slug })); ``` `revalidate` keeps its name and meaning: the page is cached for that many seconds and re-rendered in the background when stale. Next.js needs `generateStaticParams` returning `[]` to make a dynamic route cacheable; Nowaki doesn't. ```tsx // Next.js (the compare app with --isr) export const revalidate = 60; export function generateStaticParams() { return []; } // Nowaki (the compare app with --isr) export const revalidate = 60; ``` On `nowaki start` the ISR cache lives in the Rust front, per process, and responses carry `x-nowaki-cache: HIT | STALE | MISS`. The cache varies by what the render read (cookies, headers, the query); a page that reads the session or cookies is never shared. On-demand revalidation uses the same function names. Tags are set on the page instead of on each `fetch`: ```ts // Next.js const res = await fetch(url, { next: { tags: ["posts"] } }); // in a Server Action revalidateTag("posts"); revalidatePath("/blog"); // Nowaki: routes/blog/[slug].tsx export const revalidate = 60; export const tags = ({ params }) => ["posts", `post:${params.slug}`]; // in an action, API route or server function import { revalidatePath, revalidateTag } from "@nowaki-dev/runtime"; revalidateTag(`post:${ctx.params.slug}`); revalidatePath("/blog"); ``` Under `nowaki start` the purge happens before the action's response, so the redirect after it shows fresh content. The vercel adapter purges Vercel's CDN (add `@vercel/functions` to the app), and the cloudflare adapter purges the Worker's Cache API (with `CLOUDFLARE_ZONE_ID` and `CLOUDFLARE_API_TOKEN` for every data center). With several `nowaki start` instances, send `POST /__nowaki/revalidate` to each (`NOWAKI_REVALIDATE_SECRET`). ## 6. Client components → islands A `"use client"` component becomes a file in `islands/`. Drop the directive, import hooks from `preact/hooks`, and switch React-only props: ```tsx // benchmarks/compare/apps/next/components/Search.tsx "use client"; import Link from "next/link"; import { useEffect, useState } from "react"; // ... setQ(e.target.value)} /> ``` ```tsx // benchmarks/compare/apps/nowaki/islands/Search.tsx import { useEffect, useState } from "preact/hooks"; // ... setQ((e.target as HTMLInputElement).value)} /> ``` - `onChange` on a text input fires on every keystroke in React. In Preact it is the DOM `change` event (on commit); use `onInput` for each keystroke. - `className` → `class` (both work in Preact). - The rest of the component (state, effects, `fetch`) is the same code. A page or server component imports the island and renders it with props; only that island hydrates. The props must be serializable (they are written into the HTML). Hydration can be deferred per use: ```tsx // hydrate on load (default) // when scrolled into view // when the browser is idle // no server render ``` Things a client component does with `next/navigation` hooks: | Next.js | In an island | |---|---| | `usePathname()` | `location.pathname`, or `routePath(location.href)` for the path without basePath and locale | | `useSearchParams()` | `new URL(location.href).searchParams` | | `useParams()` | pass the params from the page as props | | `useRouter().push(url)` | `location.assign(href(url))` (a full load; see [gaps](#what-has-no-equivalent)) | | `useRouter().refresh()` | `location.reload()` | Nowaki also has Jetstream islands (`export const live`), whose state stays on the server and which ship no component JS. Next.js has no counterpart; see the Jetstream guide in [docs/guides/](./guides/). ## 7. Server Actions → actions and server functions A form that posts to a Server Action becomes a page `action`. It runs for every method but GET, HEAD and OPTIONS, reads the body with `ctx.formData()` (a `FormData`, as in Next.js), and usually redirects (Post/Redirect/Get). The form is a plain `
`, so it works without JavaScript. ```tsx // benchmarks/compare/apps/next/app/contact/page.tsx import { redirect } from "next/navigation"; import { Contact } from "../../lib/contact"; async function submit(form: FormData) { "use server"; const ok = Contact.safeParse(Object.fromEntries(form)).success; redirect(ok ? "/contact?sent=1" : "/contact?error=1"); } export default async function ContactPage({ searchParams }: { searchParams: Promise> }) { const query = await searchParams; return (
{"sent" in query &&

Thanks, your message was sent.

} {/* fields */}
); } ``` ```tsx // benchmarks/compare/apps/nowaki/routes/contact.tsx import type { LoaderContext } from "@nowaki-dev/runtime"; import { Contact } from "../lib/contact.ts"; export const loader = ({ url }: LoaderContext) => ({ sent: url.searchParams.has("sent"), error: url.searchParams.has("error"), }); export async function action(ctx: LoaderContext) { const form = await ctx.formData(); const ok = Contact.safeParse(Object.fromEntries(form)).success; return ctx.redirect(ok ? "/contact?sent=1" : "/contact?error=1"); } export default function ContactPage({ data }: { data: { sent: boolean; error: boolean } }) { return (
{data.sent &&

Thanks, your message was sent.

}
{/* fields */}
); } ``` Both accept urlencoded and `multipart/form-data` bodies (file inputs arrive as `File`). A page has one `action`; a page with several forms tells them apart with a field (`