Docs

@avelonjs

next

Next.js adapter

@avelonjs/next

@avelonjs/next is the v1 adapter. It turns a RouteManifest into Next's file router, serves writes as generated server actions, wraps pages around the core kernel, and bridges middleware.ts. Reach for it when the application is a Next app and you want typed routes/web.ts without putting Next types in @avelonjs/core.

The adapter is a translation layer at three seams: mount, toRequest, and toResponse. Middleware, binding, validation, and exception mapping stay in the kernel (D26).

Installation

bun add @avelonjs/next

Run reeve route:sync during dev and build. At runtime, attach the registered routes to the kernel in avelon.config.ts:

import { NextAdapter, Route } from '@avelonjs/next'
import { createKernel, defineConfig } from '@avelonjs/core'
import './routes/web'

const adapter = new NextAdapter({ root: process.cwd() })
defineConfig({
  name: 'app',
  adapter,
  drivers: {},
})

adapter.attach(Route.manifest(), { kernel: createKernel() })

Basic Usage

import { Route } from '@avelonjs/next'
import { HomeController } from '@/app/Http/Controllers/HomeController'
import { PostController } from '@/app/Http/Controllers/PostController'

Route.get('/', HomeController, 'index').name('home')

Route.middleware('auth').group(() => {
  Route.resource('posts', PostController).bind('post', 'Post')
})

reeve route:sync and NextAdapter.mount replace app/(web) and app/(api) after rendering the router in memory. Each generated page calls its controller through page:

// Generated by `reeve route:sync`. Do not edit.
import { PostController } from '@/app/Http/Controllers/PostController'
import { page } from '@avelonjs/next'

export const dynamic = 'force-dynamic'

export default page(PostController, 'show', '/posts/{post}')

In a view or client component, import url from the generated module to link to a page:

import { url } from '@/framework/routing/urls.generated'

const home = url('home')
const issue = url('posts.show', { post: 42 }) // /posts/42

TypeScript rejects a missing page or parameter. The helper encodes parameter values and needs no controller imports or runtime route registration.

Writes become server actions in framework/routing/actions.generated.ts. .api() additionally generates app/(api)/api/.../route.ts so JSON URLs do not collide with pages.

reeve route:sync --check compares the generated files with routes/web.ts without writing or mounting the adapter. It exits 0 when they match. For drift it lists each missing, changed, or stale path relative to the app root and exits 1. Run reeve route:sync to repair the files.

Generated API handlers return Fetch Response objects, preserving action status codes and stream content types. Route generation rejects traversal segments, conflicting dynamic parameter names, and duplicate server action exports before removing generated files. Named route and page URL parameters are percent-encoded.

Capabilities

CapabilityValueMeaning
fileSystemRoutingtruemount() writes framework-owned files.
serverActionstrueRoute.post() is served as a generated server action.
streamingtrueThe kernel may return StreamResult.
edgeMiddlewarefalseNext 16 Proxy middleware defaults to Node (D27).

serverActions selects the write transport. It does not gate whether a write route exists.

Request Lifecycle

page() and dispatch() convert native Next inputs with toRequest, call kernel.dispatch, then toResponse. Redirects throw NextRedirect with a NEXT_REDIRECT digest so Next navigation keeps propagating. Validation failures return { kind: 'action', ok: false, errors } for useActionState.

Server actions and multipart .api() requests pass text as strings and uploads as File objects in request.body for controller validation. Repeated fields keep the last submitted value, even when entries mix text and files. Server actions reserve _method and route parameter names: they use the last text value for routing and omit those fields from the body.

middleware.ts calls middleware(request). Routes that declare auth redirect to /login when no cookies or Authorization header are present; everything else returns { kind: 'next' }.

Method Reference

Method / exportSignatureDescription
NextAdapterclass NextAdapterFile-routing adapter implementing the frozen Adapter contract.
NextAdapter.mount(manifest, options) => Promise<MountResult>Writes the router and binds the kernel.
NextAdapter.attach(manifest, options) => voidBinds kernel and manifest without rewriting generated files.
NextAdapter.registerViews(views) => voidMaps string view tokens to React components for toResponse.
NextAdapter.toRequest(native) => Promise<HttpRequest>Converts page props, FormData, or Request. Unparseable bodies become body: null.
NextAdapter.toResponse(result) => Promise<NextNativeResponse>Converts kernel results. Redirects throw NextRedirect.
nextCapabilitiestypeof nextCapabilitiesLiteral capability object used by CLI and codegen.
bindAdapter(adapter | undefined) => voidRecords the adapter generated helpers dispatch through.
getAdapter() => NextAdapterReturns the bound adapter or throws.
setRuntimeBoot(boot | undefined) => voidRegisters a boot function page and dispatch call when unbound.
ensureAdapter() => Promise<NextAdapter>Returns the bound adapter, booting first when needed.
page(controller, action, uri) => NextPageNext page wrapper used by generated page.tsx.
NextPage(props: PageProps) => Promise<ReactNode>Return type Next's AppPageConfig accepts.
dispatch(controller, action, uri, formData) => Promise<NextNativeResponse>Server-action entry used by generated writes.
handleRoute(controller, action, uri, request, params?) => Promise<NextNativeResponse>Fetch request entry used by .api() files.
reportFailure(scope, uri, error) => voidWrites a request failure and its cause chain to stderr.
reportMappedFailure(scope, uri, result) => voidWrites a 5xx action result the kernel mapped; input failures stay unlogged.
middleware(request, routes?) => Promise<NextNativeResponse>proxy.ts / middleware.ts bridge. Pass generated routes on the Node proxy.
MiddlewareRouteinterfaceMethod, path, and middleware aliases for Edge auth.
setCookie(name, value, options?) => voidQueues a cookie write for the current Next request.
clearCookie(name, options?) => voidQueues a cookie deletion and forwards path and domain.
PendingCookieinterfaceQueued cookie name, value, and options.
ViewRegistrytypeString view tokens mapped to functions returning ReactNode.
formProps(name, params?) => { action, method, fields }Hidden fields and action export for a named write route.
generateRouter(manifest, root, options) => Promise<readonly string[]>Replaces managed routes and returns the generated paths.
checkRouter(manifest, root, options) => Promise<readonly RouterDifference[]>Returns { path, status } for each missing, changed, or stale path.
findMountedRoute(controller, action, uri) => RouteDefinitionResolves a generated helper back to its manifest entry.
Route.get(path, controller, action?) => RouteBuilderRegisters a GET route.
Route.post(path, controller, action?) => RouteBuilderRegisters a POST route.
Route.put(path, controller, action?) => RouteBuilderRegisters a PUT route.
Route.patch(path, controller, action?) => RouteBuilderRegisters a PATCH route.
Route.delete(path, controller, action?) => RouteBuilderRegisters a DELETE route.
Route.resource(name, controller) => ResourceBuilderExpands the seven resource routes.
Route.middleware(...names) => { group }Applies middleware inside a group.
Route.prefix(prefix) => { group }Prefixes routes inside a group.
Route.all() => readonly RouteDefinition[]Returns registrations.
Route.manifest(version?) => RouteManifestBuilds a mountable manifest.
Route.find(name) => RouteDefinitionFinds a named route or throws.
Route.reset() => voidClears registrations.
RouteBuilder.name(name) => thisSets the stable route name.
RouteBuilder.middleware(...names) => thisAppends middleware aliases.
RouteBuilder.bind(param, model) => thisMarks a path parameter for binding.
RouteBuilder.api() => thisAdditionally generates a JSON route handler.
ResourceBuilder.bind(param, model) => thisBinds member parameters.
ResourceBuilder.only(...actions) => thisKeeps named resource actions.
ResourceBuilder.except(...actions) => thisDrops named resource actions.
ResourceBuilder.api() => thisMarks remaining resource routes as .api().
route(name, params?) => stringFills {param} placeholders. null is a missing parameter, not a TypeError.
exportName(definition) => stringStable generated export for a write route.
uriToSegments(uri) => stringConverts /posts/{post} to posts/[post].
nativeToRequest(native) => Promise<HttpRequest>Low-level native conversion. Method override accepts PUT, PATCH, and DELETE.
kernelToResponse(result) => Promise<NextNativeResponse>Low-level result conversion.
toHttpResponse(response: NextNativeResponse) => ResponseConverts adapter results into Fetch responses for generated API handlers.
NextRedirectclass NextRedirect extends ErrorControl-flow throw with a NEXT_REDIRECT digest.
isNextControlFlow(error: unknown) => booleanTrue for Next navigation throws.
PagePropsinterfaceAsync Next page props.
NextNativeRequesttypepage, form, or http native inputs.
NextNativeResponsetypeView, action, redirect, stream, or next.
NextAdapterOptionsinterfaceroot plus optional capability overrides.

Testing

Mount the adapter against a temp directory and call page / dispatch with the same controllers the generator would import. Point the kernel at FakeDatabase when a page loads models.

import { NextAdapter, Route, page } from '@avelonjs/next'
import { createKernel } from '@avelonjs/core'

const adapter = new NextAdapter({ root: tempDir })
await adapter.mount(Route.manifest(), { kernel: createKernel() })
const Page = page(PostController, 'index', '/posts')
await Page({})
bun test
bun run typecheck