Docs

Guide 00

Getting started

00. Getting started

Build a greeting app with 2 pages, a validated form, and kernel tests. The app runs inside a clone of Avelon and doesn't need a database or credentials.


What You Need

ToolVersionWhy
Bun1.3.14The pinned toolchain. 11-runtime.md has the runtime matrix.
Next16.2.12@avelonjs/next is the v1 adapter and targets the App Router.
React19.2.0Server components render the views the kernel returns.

Install the pinned Bun version on Linux or macOS:

curl -fsSL https://bun.com/install | bash -s bun-v1.3.14

The app's package.json installs Next and React. The runtime matrix covers deployment.


Create a Standalone App

From a checkout with dependencies installed (bun install --frozen-lockfile), run:

bun run create:app ../my-app
cd ../my-app
bun install
bun run check
bun run dev

Then:

  • Open http://localhost:3000
  • Enter a title and submit the form. A server action validates the title and redirects to its slug preview
  • The app's README points to the route, controller, view, and test, so you can change one piece at a time

To try the production build, stop the dev server and run bun run build, then bun run start.

The directory can be new or empty. You can move it after creation, since its manifest uses published package versions.

Without a checkout, this creates the same app from the published CLI:

bunx --package @avelonjs/cli reeve new my-app

Run an Example First

git clone https://github.com/yannelli/avelon.git
cd avelon
bun install --frozen-lockfile
bun run dev:gazette

Open http://localhost:3010. Isle Gazette is a newspaper with authors, issues, subscribers, and a queued listener.

Two more apps run from the same clone:

CommandAppPort
bun run dev:gazetteIsle Gazette, the reference application3010
bun run dev:docsThese docs, as an Avelon app3011
bun run dev:starterSaaS starter with in-memory drivers3012

Where a New App Lives

The rest of this guide builds a greeting app by hand, using the framework source from your checkout.

Use examples/hello/ for this version of the tutorial. Its workspace:* dependencies and shared TypeScript config refer to the monorepo. For a standalone project, use the generator above.

Stop Gazette with Ctrl+C, then run these from the repository root:

mkdir -p examples/hello/{app/Http/Controllers,app/Http/Requests,routes,src,tests}
mkdir -p examples/hello/resources/views/{layouts,pages}

Every file in the next section goes under examples/hello/. The first routes use these modules:

FileWhat lives there
routes/web.tsEvery route in the application
app/Http/Controllers/GreetingController.tsOne method per route
resources/views/tokens.tsOpaque view names the controller returns
resources/views/pages/greeting.tsxThe React component behind a token
resources/views/registry.tsxTokens mapped to components
resources/views/layouts/AppLayout.tsxThe root layout the generated router re-exports
src/boot.tsConfig, routes, kernel
src/boot-runtime.tsKernel and adapter attachment
src/boot-next.tsView registration in Next's rendering layer

The Application

Step 1 - Add the Project Files

package.json. The generate script runs reeve route:sync, which writes the Next router from routes/web.ts.

{
  "name": "@avelonjs/hello",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "generate": "reeve route:sync",
    "dev": "bun run generate && bun run --bun next dev --port 3013",
    "typecheck": "tsc --noEmit"
  },
  "dependencies": {
    "@avelonjs/core": "workspace:*",
    "@avelonjs/next": "workspace:*",
    "next": "16.2.12",
    "react": "19.2.0",
    "react-dom": "19.2.0"
  },
  "devDependencies": {
    "@avelonjs/cli": "workspace:*",
    "@types/bun": "1.3.14",
    "@types/node": "^26.4.0",
    "@types/react": "19.2.2",
    "@types/react-dom": "19.2.2",
    "typescript": "5.9.3"
  }
}

tsconfig.json. Generated pages import through the @/* path.

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "types": ["bun"],
    "jsx": "react-jsx",
    "plugins": [{ "name": "next" }],
    "paths": { "@/*": ["./*"] }
  },
  "include": [
    "src",
    "app",
    "routes",
    "resources",
    "tests",
    "framework",
    "next.config.ts",
    "instrumentation.ts",
    "next-env.d.ts"
  ]
}

next.config.ts. The Avelon packages ship TypeScript source, so Next transpiles them.

import path from 'node:path'
import { fileURLToPath } from 'node:url'
import type { NextConfig } from 'next'

const root = path.dirname(fileURLToPath(import.meta.url))

const config: NextConfig = {
  outputFileTracingRoot: path.join(root, '../..'),
  transpilePackages: ['@avelonjs/core', '@avelonjs/next'],
}

export default config

Step 2 - Add the Route and Controller

routes/web.ts. One file answers "what URLs does this application serve".

import { Route } from '@avelonjs/next'
import { GreetingController } from '../app/Http/Controllers/GreetingController'

/** Every route in the application, in one file. */
export function defineWebRoutes(): void {
  Route.get('/', GreetingController, 'index').name('home')
  Route.get('/greet/{name}', GreetingController, 'show').name('greet.show')
}

defineWebRoutes()

app/Http/Controllers/GreetingController.ts. A controller method returns a result. It doesn't render. view() names a token and hands over props.

import { view, type HttpRequest } from '@avelonjs/core'
import { GreetingView } from '../../../resources/views/tokens'

export class GreetingController {
  index() {
    return view(GreetingView, { name: 'world' })
  }

  show(request: HttpRequest) {
    return view(GreetingView, { name: request.params.name ?? 'world' })
  }
}

Step 3 - Add the Views

resources/views/tokens.ts:

/** Opaque view token. Core never inspects it. */
export const GreetingView = 'greeting'

resources/views/pages/greeting.tsx:

export function GreetingPage({ name }: { readonly name: string }) {
  return (
    <main>
      <h1>Hello, {name}.</h1>
    </main>
  )
}

resources/views/registry.tsx. The adapter resolves tokens through this map, so controllers have no React import.

import type { ViewRegistry } from '@avelonjs/next'
import { GreetingPage } from './pages/greeting'

/** View tokens mapped to React components. */
export const views: ViewRegistry = {
  greeting: (props) => (
    <GreetingPage name={'name' in props && typeof props.name === 'string' ? props.name : 'world'} />
  ),
}

resources/views/layouts/AppLayout.tsx. reeve route:sync writes app/(web)/layout.tsx as a re-export of this file, so export all 3 of these:

  • default
  • metadata
  • viewport
import type { Metadata, Viewport } from 'next'
import type { ReactNode } from 'react'
import { ensureBooted } from '@/src/boot-next'

export const metadata: Metadata = { title: 'Hello Avelon' }

export const viewport: Viewport = { width: 'device-width', initialScale: 1 }

export default async function AppLayout({ children }: { readonly children?: ReactNode }) {
  await ensureBooted()
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

Step 4 - Add the Boot Files

src/boot.ts. Config, routes, kernel. Driver constructors go here or in avelon.config.ts, and nowhere under app/.

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

export function boot() {
  defineConfig({ name: 'hello', drivers: {} })
  Route.reset()
  defineWebRoutes()
  return createKernel()
}

src/boot-runtime.ts attaches the kernel and routes without loading views.

import { NextAdapter, Route, getAdapter, setRuntimeBoot } from '@avelonjs/next'
import { boot } from './boot'

let booting: Promise<void> | undefined

export async function ensureRuntimeBooted(): Promise<void> {
  if (booting !== undefined) {
    await booting
    return
  }
  booting = (async () => {
    try {
      getAdapter()
      return
    } catch {
      // First request in this process.
    }
    const kernel = boot()
    const adapter = new NextAdapter({ root: process.cwd() })
    adapter.attach(Route.manifest(), { kernel })
  })()
  try {
    await booting
  } catch (error) {
    booting = undefined
    throw error
  }
}

setRuntimeBoot(ensureRuntimeBooted)

src/boot-next.ts registers views from the layout:

  • Next transforms the 'use server' exports used by forms in its rendering layer
  • The instrumentation layer must not import the views
import { getAdapter } from '@avelonjs/next'
import { views } from '../resources/views/registry'
import { ensureRuntimeBooted } from './boot-runtime'

export async function ensureBooted(): Promise<void> {
  await ensureRuntimeBooted()
  getAdapter().registerViews(views)
}

instrumentation.ts. Next calls register at process start.

export async function register(): Promise<void> {
  if (process.env.NEXT_RUNTIME === 'edge') return
  const { ensureRuntimeBooted } = await import('./src/boot-runtime')
  await ensureRuntimeBooted()
}

Generate the Router and Run It

Step 1 - Install and Start

From the repository root, install again so Bun adds the new workspace to its lockfile:

bun install
cd examples/hello
bun run dev

generate prints what it wrote:

Mounted 2 route(s). Wrote 5 file(s).

Those 5 files are:

  • the 2 pages under app/(web)/
  • their layout
  • framework/routing/{manifest,urls}.generated.ts

The URL helper knows each GET route's name and path parameters. In a view, url('greet.show', { name: 'ada' }) builds /greet/ada.

These files are generated output. To change them, edit routes/web.ts and run generate again. Hand edits don't last:

  • The next sync discards any edit under app/(web)/
  • reeve bailiff fails a framework/routing/*.generated.ts file whose generator banner is gone

Step 2 - Open It

Stop the dev server before the next step and stay in examples/hello/.


Add a Write

Writes are served as generated server actions.

Step 1 - Add the Route

Add this inside defineWebRoutes():

Route.post('/greet', GreetingController, 'store').name('greet.store')

Step 2 - Validate the Input

Validate the input in a Request, app/Http/Requests/GreetRequest.ts:

import { defineRequest, type RequestSchema } from '@avelonjs/core'

export interface GreetInput {
  name: string
}

const schema: RequestSchema<GreetInput> = {
  parse(input: unknown): GreetInput {
    const record = input as Record<string, unknown> | null
    const name = typeof record?.name === 'string' ? record.name.trim() : ''
    if (name === '') {
      throw { issues: [{ path: ['name'], message: 'A name is required.' }] }
    }
    return { name }
  },
}

/** Validates the greeting form. */
export const GreetRequest = defineRequest<GreetInput>({ schema })

Step 3 - Add the Controller Method

In GreetingController.ts:

  • Add redirect to the import from @avelonjs/core
  • Add import { GreetRequest } from '../Requests/GreetRequest'
  • Add this method inside the class:
async store(request: HttpRequest) {
  const data = await GreetRequest.validate(request)
  return redirect(`/greet/${encodeURIComponent(data.name)}`)
}

Step 4 - Wrap the Action

bun run generate now writes framework/routing/actions.generated.ts with a greet_store export.

A server-component <form> takes an action returning void, so wrap it in resources/views/actions.ts:

'use server'

import { greet_store } from '../../framework/routing/actions.generated'

/** Server-component forms take an action returning `void`. The redirect propagates by throwing. */
export async function greetStore(formData: FormData): Promise<void> {
  await greet_store(formData)
}

Step 5 - Post From the Page

import { greetStore } from '../actions'

export function GreetingPage({ name }: { readonly name: string }) {
  return (
    <main>
      <h1>Hello, {name}.</h1>
      <form action={greetStore}>
        <input name="name" aria-label="Name" defaultValue="ada" />
        <button type="submit">Greet</button>
      </form>
    </main>
  )
}

Step 6 - Try It

Run bun run dev again and submit the form. The action runs GreetRequest and redirects to /greet/ada.

This form discards validation messages. To show them, use useActionState in a client component, as examples/gazette/resources/views/form.tsx does.


Test It Without a Browser

Create tests/greeting.test.ts. The tests dispatch through the kernel without starting Next.

import { expect, test } from 'bun:test'
import type { HttpRequest } from '@avelonjs/core'
import { Route } from '@avelonjs/next'
import { boot } from '../src/boot'

function request(overrides: Partial<HttpRequest> = {}): HttpRequest {
  return {
    method: 'GET',
    url: 'http://localhost/',
    params: {},
    query: {},
    headers: {},
    cookies: {},
    body: null,
    rawBody: async () => new Uint8Array(),
    aborted: false,
    ...overrides,
  }
}

test('the home route renders the greeting view', async () => {
  const kernel = boot()
  const result = await kernel.dispatch(Route.find('home'), request())
  expect(result).toMatchObject({ type: 'view', view: 'greeting', props: { name: 'world' } })
})

test('the write route redirects to the named greeting', async () => {
  const kernel = boot()
  const result = await kernel.dispatch(
    Route.find('greet.store'),
    request({ method: 'POST', url: 'http://localhost/greet', body: { name: 'ada' } }),
  )
  expect(result).toMatchObject({ type: 'redirect', location: '/greet/ada' })
})

test('the write rejects a blank name', async () => {
  const kernel = boot()
  const result = await kernel.dispatch(
    Route.find('greet.store'),
    request({ method: 'POST', url: 'http://localhost/greet', body: { name: ' ' } }),
  )
  expect(result).toMatchObject({
    type: 'action',
    ok: false,
    errors: { name: ['A name is required.'] },
  })
})

Run the tests and the type check:

bun test
bun run typecheck

Run the Linter

Bailiff reads the architecture, so a shortcut fails the build instead of the review.

Step 1 - Check the Clean App

bunx --no-install reeve bailiff
Bailiff is clean.

Step 2 - Break a Rule

Add a write action to the end of GreetingController that skips the Request:

async destroy() {
  return redirect('/')
}

Run Bailiff again:

bunx --no-install reeve bailiff
app/Http/Controllers/GreetingController.ts:19:3 @avelonjs/bailiff/require-request Write action destroy() must validate through a Request.

1 error, 0 warnings. Run reeve bailiff --explain <rule> for the reason behind a rule.

Step 3 - Read the Reason

reeve bailiff --explain require-request prints why the rule exists. Remove destroy() before running the check again.

The Bailiff guide lists the rules.


Generate Instead of Typing

Generators write each file where the directory map puts it, and every file they write passes bun run check.

In an app created with reeve new, a model with a migration, a factory, a policy, and a resource controller is one command:

bunx --no-install reeve make:model Post -mfcp --resource
created  app/Models/Post.ts
created  app/Wards/PostWard.ts
created  database/migrations/20260901120000_create_posts_table.ts
created  database/migrations/index.ts
created  database/factories/PostFactory.ts
created  app/Policies/PostPolicy.ts
created  app/Http/Controllers/PostController.ts
created  app/Http/Requests/PostRequest.ts
created  app/Http/Requests/DestroyPostRequest.ts
created  resources/views/pages/posts.tsx
updated  app/Providers/AppProvider.ts

Next:
  Pass the migration list to your database driver in avelon.config.ts, for example:
    import { migrations } from './database/migrations'
    database: createPostgresDatabase({ url: process.env.DATABASE_URL, migrations })
  Route it in routes/web.ts, then run bun run generate:
    Route.resource('posts', PostController)

Every model gets a ward, because Bailiff fails a model without one. Reeve also:

  • registers the ward and the policy in registerApp() of app/Providers/AppProvider.ts, which avelon.config.ts calls at boot
  • adds the migration to the list in database/migrations/index.ts

Routes stay yours to place. When the file a generator exists to write is already there, it writes nothing.

In This Tutorial's App

examples/hello/ has no provider, so reeve prints the registration lines instead.

Before generating a model or factory there:

  1. Add "@avelonjs/orm": "workspace:*" to dependencies
  2. Add "@avelonjs/assay": "workspace:*" to devDependencies
  3. Run bun install from the repository root

08-cli.md is the full command list, and bare reeve opens the TUI.


Add a Database

The app above declares drivers: {}. To add Postgres:

  1. Declare @avelonjs/postgres as a workspace dependency
  2. Install from the repository root
  3. Configure the driver in avelon.config.ts

reeve make:migration create_greetings_table writes a migration and the migrations list in database/migrations/index.ts.

Import this config from src/boot.ts in place of the inline defineConfig(...) call:

import { defineConfig } from '@avelonjs/core'
import { createPostgresDatabase } from '@avelonjs/postgres'
import { migrations } from './database/migrations'

export default defineConfig({
  name: 'hello',
  drivers: {
    database: createPostgresDatabase({
      url: process.env.POSTGRES_URL ?? 'postgresql://postgres:avelon@127.0.0.1:5432/avelon',
      migrations,
    }),
  },
} as const)

reeve migrate loads avelon.config.ts and applies the pending migrations.

Read next:

  • 05-database.md covers models and migrations
  • 04-drivers.md covers what a driver must implement, and how capability narrowing removes methods a driver can't serve

Where to Go Next

DocRead it for
01-thesis.mdThe problem this framework is answering
03-architecture.mdPackages, the adapter contract, the request lifecycle
05-database.mdModels, the query IR, migrations
06-authorization.mdPolicies for abilities, Wards for rows
07-events.mdEvents, listeners, queued delivery
08-cli.mdEvery reeve command
09-bailiff.mdThe architecture rules and why each exists
11-runtime.mdBun, Vercel, and what runs where