#Migrating from Next.js
Move a Next.js App Router or Pages Router site to Krate.
Krate's pages, routing, and <Link> semantics mirror Next.js closely, so most
files need small edits. The biggest conceptual change: there is no React
runtime - components are plain functions returning JSX, and state uses
signals.
#Concept mapping
| Next.js | Krate |
|---|---|
useState |
createSignal (const [v, setV] = createSignal(0)) |
useEffect |
createEffect |
useMemo |
createMemo |
useRef |
ref={el => ...} / useRef (krate runtime) |
className |
class |
app/page.tsx |
src/pages/index.tsx |
app/blog/[slug]/page.tsx |
src/pages/blog/[slug].tsx |
layout.tsx |
_layout.tsx (nearest wins; stacks) |
generateStaticParams |
generateStaticParams (same shape) |
export const revalidate / dynamic |
export const revalidate / dynamic (ISR, SSR) |
async server components, await fetch() |
async components render per request on the SSR sidecar; see Server Components |
fetch(url, { next: { tags, revalidate } }), unstable_cache |
same, cached and tagged by the runtime; see Caching and Revalidation |
revalidatePath / revalidateTag (next/cache) |
same names from @krate/runtime/server |
"use client" |
kept: a client boundary inside server component trees |
template.tsx |
_template.tsx (remounts on every navigation) |
(group), @slot, default.tsx, (.)x |
same directory names under src/pages; see Routing |
next/link |
global <Link> (or <a data-krate-link>) |
next/navigation (usePathname, useParams, useSearchParams, useRouter, useSelectedLayoutSegment(s)) |
the same hooks from @krate/runtime |
notFound(), forbidden(), unauthorized(), redirect() |
the same names from @krate/runtime/server; forbidden.tsx / unauthorized.tsx become 403.tsx / 401.tsx |
next/image |
global <Image> |
next/head |
global <Head> |
API routes app/api/x/route.ts |
src/api/x.ts (JS) or src/api/x.go (Go) |
"use server" actions |
"use server" module; see Server Actions |
#Use the migration CLI
Start with a dry run from the Next.js project root:
krate migrate nextjsThe planner detects App Router (app/) and Pages Router (pages/) files and
prints every copy plus every item it will not rewrite. Apply it with:
krate migrate nextjs --apply
krate migrate nextjs --report migration-report.jsonThe dry run marks every file that already exists (tsconfig.json,
middleware.ts, package.json, ...) and says so at the end: --apply then
needs --force. The originals are backed up first and krate migrate rollback
restores them.
Add --update-package to also add krate scripts and @krate/* dependencies
(pinned to the version of the compiler you run) and preact to package.json;
package.json already exists, so pair it with --force. The plan lists each
script it replaces and each dependency it adds or keeps. Next.js dependencies are
left in place until the migrated app builds cleanly.
The first pass:
- copies
app/**/page.*,pages/**/*, layouts, templates,loadingfiles,not-foundanderrorfiles, and API handlers intosrc/pages/andsrc/api/, keeping route groups,@slotdirectories, slotdefault.tsxfiles and intercepting(.)xsegments in place (the Krate file router understands them); - copies Pages Router
_appand wraps it as the root_layout.tsxshell; - copies app-local relative imports under
src/migrated/and rewrites the migrated route imports to point at them; - follows imports from the migrated files to project modules outside
app/(relative imports and tsconfigpaths/baseUrlaliases such as@/*, includingextends) and applies the same Next import rewrites to them (next/link,next/navigation,next/cache,next/headers,next/dynamic,next/server,Metadatafromnext). These modules stay where they are and are rewritten in place, so the plan lists them withtargetequal tosource; each is backed up first andkrate migrate rollbackrestores it. Because they overwrite your source,--applyneeds--forcewhen any are planned. Workspace packages that importnext/*are outside the project and are listed as manual items; - keeps
"use client"(client boundary inside server component trees) and strips default imports fromnext/link,next/image, andnext/head(Krate exposes those as globals); - translates static
next.config.*redirects, rewrites, headers,basePath, and image breakpoints/formats/remote patterns into the generated config (also whenredirects(),rewrites()orheaders()is anasyncfunction that returns a literal array), maps static rootmetadatatositeconfig, and wraps static, synchronous, and asyncgenerateMetadataresults in<Head>. A key it cannot prove static is reported as manual work on its own; the other keys still translate, and so does each rule: in aheaders()array, the static entries translate while a computed one (a helper call,value: compute()) is reported with its source path. A redirect, rewrite or header rule withhasormissingis never translated, because Krate matches on the path only and an unconditional copy would apply to every request (a guarded/storeredirect would send/storeaway for everyone); each is reported with its source and condition, and the hint points atmiddleware.ts. Identical duplicate rules in the output are warned about. When headers could not be translated and the config (or a local module it imports) mentionsContent-Security-Policy,Strict-Transport-Security,X-Frame-Optionsor similar, a separate item says the security headers were not migrated.krate.config.tscan import a local module, so a helper that builds static headers can be imported there; values that depend on the request, such as a CSP nonce, belong inmiddleware.ts. Every othernext.configkey gets its own item with a hint instead of one generic warning:transpilePackages,output: 'standalone', computedimages.remotePatternsorenv,experimentalflags, and aloadEnvConfig(...)call whose path is not static. When the path is static (a literal,path.resolve(__dirname, '../..'),join(process.cwd(), '..', '..'),fileURLToPath(new URL('../..', import.meta.url))), the migration writes the matchingenvDirand there is no item. A staticserverExternalPackageslist and staticoutputFileTracingIncludesglobs are carried over to the Krate keys of the same name (see Self-hosting); computed ones get an item. Anasyncpage keepsasyncand its wrapper isasynctoo, so the page renders per request; - keeps
export const revalidate,dynamicanddynamicParamson pages, which Krate honors, and notes in the plan what each does (ISR, SSR, 404 for unlisted params); the same exports in a layout are manual work; - rewrites
middleware.tsto the standardRequest/ResponseAPI, including aNextResponseclass (aResponsesubclass:new NextResponse(body, init),redirect,json,next,rewrite,cookies;next({ request: { headers } })reaches layouts throughheaders()), static/local matcher checks, and cookie/IP/geo helpers; computedconfig.matcherarrays are checked at runtime. The Next.js 16proxy.ts(root orsrc/, aproxyfunction or a default export) is migrated the same way and written tomiddleware.ts, the name Krate loads (--applymoves the originalproxy.tsinto the backup); when both files exist onlyproxy.tsis migrated and the other is a manual item; - copies static
favicon.ico,icon.*andapple-icon.*files from the app root topublic/and links the root ones from the generatedheadconfig (<link rel="icon">,<link rel="apple-touch-icon">). Icons inside a segment are copied but need their<link>added by hand. Dynamicicon.tsxandapple-icon.tsxare manual items; - keeps the public URL of route handlers outside
app/api: they move under/api/, and the plan adds arewritesentry from the old path (/r/[code]becomes/r/:codeto/api/r/:code; catch-alls use:path+and:path*).krate serveandkrate devanswer such a rewrite from the API handler. A handler at the app root (app/route.ts) is a manual item, because a rewrite for/would shadow the home page. Deploy targets that do not run the Krate server may not apply the rewrite; - leaves inline
"use server"functions (a directive inside a function body, the Auth.jssignOutpattern) as they are: the build hoists them into server actions, sealing the values they close over (see Server Actions). One inside a"use client"module is flagged as manual work, because it fails the build withKR7001there as it does in Next.js; - strips root-layout
<html>/<body>wrappers and carries their attributes (lang,className,data-*, ...) into a<Head>with<html>and<body>elements, which set the attributes of the document elements (see Document attributes);suppressHydrationWarningis dropped; - maps
forbidden.tsxto403.tsxandunauthorized.tsxto401.tsx(the Next.js 15.1authInterruptspages), and drops theexperimental.authInterruptsflag, becauseforbidden()andunauthorized()always work; - maps
not-found.tsxto404.tsxanderror.tsxtoerror.tsxin the same directory (route groups kept), where they are native segment pages: the nearest not-found page answersnotFound()and unmatched URLs inside the layouts, anderror.tsxis the segment's error page and client error boundary withreset.global-error.tsxbecomes the rooterror.tsx(remove the<html>and<body>it renders; Krate's root layout provides them), or a manual item when a rooterror.tsxexists too. A directory that has a layout, template, loading, error or not-found file keeps its page in that directory (dashboard/index.tsx) so those files wrap it. A route segment named like a Krate special file (error,loading,not-found,layout,template,404,500,403,401,forbidden,unauthorized,index) also keeps its page in the directory (auth/error/index.tsx), so/auth/errorstays a page; - maps
next/navigationonto the runtime:usePathname,useParams,useSearchParams,useRouteranduseSelectedLayoutSegment(s)come from@krate/runtime(see Router hooks), andnotFound,redirect,permanentRedirect,forbiddenandunauthorizedfrom@krate/runtime/server(from@krate/runtimein a"use client"file). No helper file is generated. Names with no equivalent (RedirectType,unstable_rethrow,useServerInsertedHTML) stay onnext/navigationand are listed as manual work.next/headersandnext/cachemap to@krate/runtime/server, rewrites commonnext/serverAPI helpers, and mapsnext/dynamicloaders to Reactlazy(). Next accepts a loader that resolves to a module or straight to a component, butlazy()needs{ default }, so.then((m) => m.Pane)becomes.then((m) => ({ default: m.Pane })),.then(() => Pane)becomes.then(() => ({ default: Pane })), and any other loader that post-processes the import is wrapped in a smallasLazyModulehelper added to the file. Adynamic(() => import('./x'), { ssr: false, loading })call (with or without a type argument,dynamic<Props>(...)) becomes a module-levellazy()plus a component that renders theloadingfallback until it has mounted in the browser, then the lazy component inside a<Suspense>with the same fallback (shown while the chunk loads, as in Next.js): the page HTML holds the fallback, the component lives in its ownlazy-*.jschunk and the build still renders it once, hidden, so a viewer that toucheswindowwhile rendering needs a real-React island (see React compatibility) or a guard. Aloadingthat is not an arrow function returning JSX or a component name, andssr: falseoutside a top-levelconst, are manual items; - moves
@react-three/fiberand@react-three/dreicode to@krate/threewhen every fiber and drei API the project's modules use is provided (drei'sOrbitControls,EnvironmentwithLightformerchildren or amap, anduseGLTFcome from@krate/three/drei), and adds@krate/threetopackage.json(a manual item without--update-package). The scene then runs on Krate, or on the Preact island of a"use client"component, instead of a real-React island that ships React, react-dom and a second copy of the React libraries around the canvas. One unsupported API (another drei helper,<Environment preset>, fiber'sreconciler, a package built on fiber such as@react-spring/three) keeps every fiber module as it is, because they render each other's components in one canvas, and each blocking use is listed as a manual item. Keep@react-three/fiberand drei installed while a real-React island renders one of the 3D components: there the build runs@krate/threeas fiber; - moves
react-konvacode to@krate/konvawhen every react-konva API the project's modules use is provided (Stage, the layers and shapes, Transformer,useStrictMode,useContextBridge), and adds@krate/konvatopackage.json(a manual item without--update-package). Type imports fromkonvastay as they are. The canvas then runs on Krate, or on the Preact island of a"use client"component, instead of a real-React island.KonvaRenderer, an internalreact-konva/...subpath or a package built on react-konva (such asreact-konva-utils) keeps every react-konva module as it is, and each blocking use is listed as a manual item; - converts
next/script:<Script strategy="afterInteractive">(the default) becomes a Krate<Script defer>,lazyOnloadanasyncone andbeforeInteractivea<script>inside<Head>;src,id,data-*attributes and inline children are kept.strategy="worker"and computed strategies are loaded deferred on the main thread and listed as manual items, as areonLoad,onReadyandonErrorhandlers, which a static<script>cannot run.after()fromnext/serverbecomesafterfrom@krate/runtime/serverin pages and layouts as well as route handlers; - writes
trailingSlash: "never"intokrate.config.ts(Next's URL form:/storeanswers 200,/store/redirects), or"always"whennext.configsetstrailingSlash: true, andtailwind: { enabled: true }whenpostcss.config.*uses@tailwindcss/postcssortailwindcss, andcompress: { brotli: true, gzip: true }(Next.js compresses responses unlessnext.configsetscompress: false):krate buildwrites.brand best-ratio.gzsiblings of the assets, whichkrate startsends, instead of gzipping on the fly; - keeps
NextRequestfeatures in route handlers: theRequesthasrequest.cookies(get,getAll,has, read-only) andrequest.nextUrl(aURLwithsearchParams,pathname,basePathandclone(); the pathname never includes the base path), and the handler is typed asKrateRequestfrom@krate/runtime/server.NextResponse.jsonandNextResponse.redirectcome from a small generated shim whose responses carrycookies.set/delete/get/getAll/has.after()fromnext/serverbecomesafterfrom@krate/runtime/serverand runs once the response is sent (see API routes). Only what is left is manual work:request.cookies.set/delete,request.ip,request.geo,NextResponse.rewrite/nextin route handlers, and othernext/serverhelpers such asuserAgent; - maps
next/font/googleto a generated helper and Google Fonts CSS, andnext/font/localplusgeist/font/sansandgeist/font/monoto self-hosted@font-faceCSS: eachlocalFont({ src, weight, style, variable, display, declarations, fallback })call (a singlesrcor an array of{ path, weight, style }, all literals) is replaced by an inline{ className, variable, style }object, the font files are copied topublic/migrated-fonts/, and the rules go tosrc/migrated/next-fonts.css, which the file imports.GeistSansandGeistMonouse the variable font files shipped in the installedgeistpackage.adjustFontFallbackandpreloadare ignored (Krate does not generate size-adjusted fallbacks). A call with a computed option or an importedsrcstays onnext/font/localand is reported as manual work; the other Geist fonts (pixel,serif,*-non-variable) are not mapped; - keeps
export const maxDuration = Nin API routes: Krate reads it as the route's request timeout in seconds (default 30), in every runtime and deploy target (see Timeouts). It must be a literal number; a computed value is reported as manual work. On a page it has no meaning and is dropped; - drops the other route segment config that only steers Vercel (
runtime,preferredRegion) with an info note per file and one aggregated warning, since Krate self-hosts on Node.fetchCacheis kept and reported as one aggregated manual item (set the cache option on thefetchcalls that relied on it); - creates
krate.config.tswhen the project has none, or merges missing Next-derived keys into an existing config (existing keys win); - merges/generates
tsconfig.jsonfor Krate JSX and route types; - renames reads of
process.env.NEXT_PUBLIC_NAME(and the keys of staticnext.configenv) toprocess.env.KRATE_PUBLIC_NAME, the prefix Krate inlines at build time. Values are never copied from.env*into the migrated code, so development URLs and keys cannot ship by accident. One manual item lists every variable to rename or set for the Krate build and which.envfiles define it; - moves the original Next.js route trees (
app/orsrc/app/, andpages/when it was migrated) into the backup directory on--apply, after every file is written, so Krate does not compile them next to the migrated copies. The plan says which trees move, andkrate migrate rollbackmoves them back. Files in those trees that the migrator does not copy (a README, a.txtfile) go to the backup with the tree and are listed as a warning. A tree stays in place when a migrated file is written inside it. Copied test files (*.test.*,*.spec.*,__tests__) are kept insrc/migrated/next to their modules, and their relative imports of migrated routes (./page) are re-pointed atsrc/pages/; with the originals moved aside each test runs once; - ports next-auth v5 to
@krate/authwhen it finds aNextAuth({...})config (an object, or a function returning one): the import becomesdefineAuthfrom@krate/auth,next-auth/providers/*imports become the matching@krate/authproviders,next-auth/reactbecomes@krate/auth/client, andcookies: { prefix: "authjs" }is added so the existingauthjs.*cookies and database sessions keep working.handlers,auth,signInandsignOutkeep their names, so the[...nextauth]route, server actions and server components need no edits, and@auth/drizzle-adapteris kept as is.--update-packageadds@krate/auth. A provider, option, callback, cookie override,getToken,useSessionorauth(handler)wrapper with no@krate/authequivalent is listed as manual work with what to do instead, and next-auth is never left to fail at run time as an unresolved import; - warns about script files at the project root and directly under
src/that the plan neither copies nor rewrites (auth.ts, a strayproxy.mjs, ...), skipping*.config.*,*.d.tsand test files, so nothing is dropped without a trace; - lists
instrumentation.ts,instrumentation-*.tsas manual work: Krate has no server startup hook that callsregister().
Every apply writes a rollback manifest under
.krate/migrate/nextjs-<timestamp>/. Undo with:
krate migrate rollback .krate/migrate/nextjs-<timestamp>Add --verify to build the migrated app, run krate check, and diff the built
route inventory against the migration report before you accept the migration.
Verification evaluates krate.config.ts, which imports @krate/core, so the
packages must be installed first. Before it writes anything, --apply --verify
checks that @krate/core (and any other @krate/* package a generated file
imports) resolves from the project, and stops with a message if not: run with
--update-package, install the dependencies, then re-run.
krate migrate nextjs --apply --verifyVerification fails on a build error, failing quality gate, missing route, missing API target, or extra generated route. It leaves the backup in place so you can inspect the diff and roll back. The reference-app suite runs the same check for App Router, Pages Router, and client-island/dynamic fixtures; the complex App Router fixture also runs the browser conformance suite.
The migrator intentionally reports manual work instead of guessing:
async/class page defaults with generateMetadata, getStaticProps/
getServerSideProps, middleware response rewrites, local font files with computed options, async
layouts (move the data fetching into an async child component), next/cache
exports without an equivalent (updateTag, cacheLife, cacheTag, "use cache"),
fetchCache route segment config, a default.tsx outside a parallel-route slot, nested
not-found, unresolved relative imports, and function/plugin
next.config.* files (or keys of one) are not rewritten automatically. Resolve those before
running krate build. useSelectedLayoutSegment(s) count from the layout whose
file calls them; a hook called from a shared component counts from the root.
Client components rendered inside async server components hydrate with Preact:
--update-package adds it, otherwise install preact.
#Steps
-
Scaffold & install
npx create-krate-app@latest my-site cd my-site && npm install -
Move pages. Copy
app/**/page.tsx(orpages/**) intosrc/pages/, renamingindexand stripping thepagefilename:app/page.tsx -> src/pages/index.tsx app/about/page.tsx -> src/pages/about.tsx app/blog/[slug]/page.tsx -> src/pages/blog/[slug].tsxWrap
app/layout.tsxcontent insrc/pages/_layout.tsx. -
Convert state. Replace hooks:
// Next.js const [n, setN] = useState(0); // Krate const [n, setN] = createSignal(0); // read by calling: n() (not n) -
Fix attribute names.
className->class;htmlFor->for. -
Links & images. Replace
next/link/next/imageimports with the globals<Link href="...">/<Image src width height alt>. -
Data fetching.
asyncserver components thatawait fetch()work as they do in Next.js (they render per request); tag and cache the reads withfetch(url, { next: { tags, revalidate } })and invalidate them from server actions withrevalidateTag/revalidatePath. For client-side data usecreateResource; see Data Fetching. -
Server actions & API routes. Move
"use server"functions to action modules (see Server Actions). Moveapp/api/*/route.tshandlers tosrc/api/*.tsexportingGET/POST/etc. Prefer Go routes (src/api/*.go) for hot endpoints. -
Config.
krate migrate nextjstranslates staticredirects,rewrites,headers,basePath, and commonimagessettings fromnext.config.*into the generatedkrate.config.ts. Review custom image loaders,env, experimental keys, and computed/plugin configs manually. -
Build & check.
krate build && krate check
#Gradual adoption via React interop
React interop is always on. Krate automatically rewrites React hooks
(useState, useEffect, useMemo, useReducer, useRef, useCallback,
useContext, useId) and React.* member calls to signal-based equivalents
during compilation, and auto-calls bare reads ({count} -> count()), so files
deeply tied to React hooks compile without config changes. This is a migration
aid, not a full React runtime - see
React Compatibility.
#What is intentionally different
- No
getServerSideProps/getStaticProps- use render modes (export const config = { ssr: true }, or Next-styleexport const dynamic/revalidate) and async server components. - Catch-all params (
[...slug]) are a/-joined string in the page'sparamsprop, notstring[].useParams()returns the array, like Next.js. usePathname()never has a trailing slash (/stays), whatever URL the server canonicalizes to.- Layouts are built once and cannot call
forbidden()orunauthorized()(see Forbidden and unauthorized). - React context is supported through React interop; module-level signals and props are still the lowest-overhead option.
- Streaming uses
<Suspense>with region rendering (see Rendering).
#See also
#Deploying a migrated app
A migrated app's server features (async server components, route handlers,
server actions, middleware, ISR) deploy to Vercel, Netlify, Cloudflare or a
plain Node server with krate deploy --target vercel|netlify|cloudflare|node.
Differences from Next.js on those hosts: caches are per instance (revalidatePath
and revalidateTag reach only the instance that handled the request and report
the rest under skipped), Vercel and Netlify serve prerendered pages from the
CDN before middleware runs, and Cloudflare builds fail at bundle time on Node
built-ins that Workers lack. See Deployment.
Last updated: 2026-11-17
Contributors: Noinkin