# Guren — Full Documentation > Guren is a Bun-first fullstack TypeScript framework: Laravel-style conventions, end-to-end type safety from route to React component, and mechanical verification your coding agent runs itself. Develop on Bun; deploy to Bun, AWS Lambda, Vercel, or Cloudflare Workers. Source: https://guren.dev/docs — per-page Markdown is available by appending `.md` to any docs URL. --- # Guren at a Glance The fullstack TypeScript framework that feels like Laravel, powered by Bun. ## See for Yourself A route, a controller, and a typed response in a few lines: ```ts // routes/web.ts import { Router } from '@guren/core' import TaskController from '@/app/Http/Controllers/TaskController' import DashboardController from '@/app/Http/Controllers/DashboardController' export function registerWebRoutes(router: Router): void { router.get('/tasks', [TaskController, 'index']) router.post('/tasks', [TaskController, 'store']) router.middleware('auth').group((auth) => { auth.get('/dashboard', [DashboardController, 'index']) }) } ``` ```ts // app/Http/Controllers/TaskController.ts import { Controller, paginate, type PaginatedPageProps } from '@guren/core' import { Task } from '@/app/Models/Task' import { TaskResource, type TaskResourceData } from '@/app/Http/Resources/TaskResource' import { CreateTaskSchema, ListTasksQuerySchema } from '@/app/Http/Validators/TaskValidator' import { pages } from '@/.guren/pages.gen' type TasksIndexProps = PaginatedPageProps export default class TaskController extends Controller { async index() { const { page } = this.validateQuery(ListTasksQuerySchema) const result = await Task.paginate({ page, perPage: 20, orderBy: ['createdAt', 'desc'] }) const paginator = paginate(result, { path: this.request.path ?? '/tasks' }) return this.inertia(pages.tasks.Index, { data: result.data.map((task) => new TaskResource(task).toJSON()), pagination: { meta: paginator.meta(), links: paginator.links(), }, } satisfies TasksIndexProps) } async store() { const data = await this.validateBody(CreateTaskSchema) const task = await Task.create(data) return this.redirect(`/tasks/${task?.id ?? ''}`) } } ``` Your React page receives typed props directly from the controller, with no manual API layer in between: ```tsx // resources/js/pages/tasks/Index.tsx import type { PageProps } from '@guren/inertia-client/contracts' import { pages } from '@/.guren/pages.gen' type Props = PageProps export default function TasksIndex({ data, pagination }: Props) { return (
    {data.map((task) => (
  • {task.title}
  • ))}

{pagination.meta.total} tasks

) } ``` Testing reads like plain English: ```ts const app = await TestApp.create({ boot }) await app.get('/tasks').assertOk().assertJsonCount(3, 'tasks') await app.post('/tasks', { title: 'Ship it' }).assertRedirect('/tasks') await app.actingAs(user).get('/dashboard').assertOk() ``` ## What Makes Guren Different **Bun-native from day one.** Guren runs on Bun's runtime with Hono as the HTTP layer. There is no Node.js compatibility shim, so you get Bun's fast startup, native TypeScript execution, and built-in test runner out of the box. **Laravel's developer experience, in TypeScript.** If you have used Laravel, the patterns are instantly familiar: resource routing, `Controller` base classes with `this.inertia()`, and `Model.where().orderBy().get()`. If you have not, you will find them intuitive anyway: the API reads like what it does. **End-to-end type safety.** Your Drizzle schema types flow into your Model, through your Controller, and into your React page props. Change a column name and TypeScript catches every place that needs updating, from database to browser. **Project knowledge that stays connected to code.** Guren links architecture decisions and generated spec views to the entities and paths they govern, validates those relations, and renders the whole corpus as an interactive Docs Graph during development. See [Spec-Anchored Development](./spec-anchored.md) for the complete workflow. **Batteries included, not forced.** Authentication, validation, caching, queues, mail, events, broadcasting, and scheduling are all there when you need them. Each subsystem is opt-in through ServiceProviders, so you only load what you use. **Convention over configuration.** Generate a full feature with `bunx guren add auth` or `bunx guren add resource posts`. The CLI scaffolds the files in the right place with the right structure so you spend time building features, not debating folder layout. **Router registrars over global state.** Generated apps export route registrars and pass them into `createApp({ routes })`, which keeps routing scoped to each application instance. For a deeper, honest comparison with Hono, Next.js, and Laravel, and for how Guren is designed for AI coding agents, see [Why Guren](./why-guren.md). ## Get Started Four commands. No Docker, no database server — a fresh app uses SQLite out of the box: ```bash bunx create-guren-app my-app # scaffold — accept the default prompts (SSR, SQLite) cd my-app bun install # usually a no-op: the scaffolder installs for you bun run dev # start the dev server ``` Open `http://localhost:3333` and you have a running Guren app. ## Learn More Follow this path, in order: 1. **[Quickstart](./getting-started.md)**: scaffold a project and see it running in about five minutes. 2. **[The Guren Tutorial](../tutorials/00-overview.md)**, recommended for newcomers: a hands-on fourteen-chapter course that builds a blog from an empty directory to a deployed app. Every chapter hands one slice to a coding agent and judges the result with a test and `guren gate`, so you finish having touched every core concept and knowing how to delegate the next one. 3. **Topic guides** for deep dives once you know your way around: - [Routing](./routing.md): route groups, middleware, and resource routes. - [Controllers](./controllers.md): request handling, input helpers, and validation. - [Database](./database.md): connections, Drizzle schemas, migrations, and seeding. - [Models](./models.md): the QueryBuilder, creating and updating rows, scopes, and serialization. [Relationships](./relationships.md) covers relations and eager loading. - [Frontend](./frontend.md): Inertia-powered React pages and SSR. - [Testing](./testing.md): TestApp, fluent assertions, and test utilities. - [Spec-Anchored Development](./spec-anchored.md): generated diagrams, architecture decisions, verified links, and the Docs Graph. Prefer a quick guided tour before the tutorial? [First Steps](./first-steps.md) traces one request through every layer in ten minutes. For a full reference of CLI commands, see the [CLI Reference](./cli.md). If any term is unfamiliar, check the [Glossary](./glossary.md). --- # Why Guren An honest look at where Guren fits (compared with Hono, Next.js, AdonisJS, and Laravel) and why it is built the way it is. ## The Short Version - **Choose Guren** when you are building a fullstack app (auth, database, forms, background jobs, mail) and want it all wired together, typed end to end, in one TypeScript codebase. - **Choose plain Hono** when you are building a small, stateless API service and want nothing else in the way. - **Choose Next.js** when your product is content-heavy and React-rendering-first: marketing sites, e-commerce storefronts, apps built around React Server Components. Guren also invests heavily in one thing most frameworks do not: making your project easy for **AI coding agents** to understand, extend, and verify. More on that below. ## Built for AI Coding Agents Most frameworks were designed for humans reading documentation. Guren is additionally designed for agents working inside your repository, and every scaffolded app ships that way out of the box: agent-ready by default, in the same spirit as secure by default. Three properties make the difference: **Agents can discover the project cheaply.** `bunx guren context` emits a compact map of your routes, models, controllers, and pages (add `--json` for machine-readable output). An agent gets accurate project understanding from one command instead of crawling the tree, which keeps its context window small and its assumptions correct. `bunx guren model:list` does the same for the data model. **Conventions shrink the decision space.** Controllers live in `app/Http/Controllers`, models in `app/Models`, pages in `resources/js/pages`, and `bunx guren make:feature Post --fields "title:string,body:text"` scaffolds a complete, consistent CRUD slice. When there is one obvious place and one obvious shape for everything, generated code lands right the first time far more often. **Mistakes are caught mechanically, not by review alone.** Three independent gates verify agent-written code: ```bash bunx guren check # routes ↔ controllers ↔ pages stay consistent bunx guren audit # missing validation/auth on mutating routes, raw SQL, secrets bun run typecheck # typed page props and route contracts fail the build on drift ``` Because page props, route params, and request bodies are all typed contracts, an agent that hallucinates a prop name or forgets a validation schema gets a compile error or a failing check before you read a single line of the diff. The result: less context to load, fewer degrees of freedom to get wrong, and mechanical verification of what was produced. That loop (discover, generate, verify) is what makes agent-driven development on Guren dependable rather than hopeful. **And the specification keeps itself honest.** Guren treats project knowledge by one principle: *derived where possible, declared where not, checked always*. ER diagrams, the domain model, and the screen inventory are generated from code (`bunx guren spec:generate`) and drift-gated in CI; decisions that code can't express live as ADRs whose frontmatter links them to the models they govern, validated on every change; and `bunx guren context Invoice` hands anyone, human or agent, everything the project knows about one entity, including the documents linked to it, with the checker vouching that the links are intact and the derived views current. See [Spec-Anchored Development](./spec-anchored.md) for the full loop. **And it is measured, not aspirational.** [Agents on Guren](https://github.com/gurenjs/agents-on-guren) runs 20 bug, security and feature tasks with hidden acceptance tests across three models, with and without the harness the scaffold ships: 360 runs, each one's patch, logs and verdict published. On Sonnet 5 the harness passed 60 of 60 runs against 58 of 60 bare, at 28% fewer turns and 25% lower cost. Opus 5 went 60 of 60 either way, at 26% fewer turns and 12% lower cost. On Haiku 4.5 the pass rate itself moved, 51 of 60 to 54, at 6% higher cost. Agents that had the harness ran `guren check` in 119 of their 180 runs; bare, 15. The report carries the reversals too, and the corpus surfaced a `paginate()` eager-loading bug in the ORM, since filed. ## Compared with Hono Guren's HTTP layer *is* Hono. Every request goes through Hono's router, so you stay in the same performance class — Guren adds a thin MVC layer on top, not a new server. What Hono deliberately leaves out, Guren ships: | You need | With plain Hono | With Guren | |----------|-----------------|------------| | Database access | Pick an ORM, wire it up yourself | `Model.where().orderBy().get()` on Drizzle, out of the box | | Validation | Call your schema library per handler | `this.validateBody(schema)` — 422 responses handled for you | | Authentication | Assemble sessions, hashing, middleware | `bunx guren add auth` scaffolds the whole flow | | Frontend | Separate SPA + hand-rolled API layer | Inertia-powered React pages with typed props | | Background jobs, mail, events, cache | Choose and integrate libraries | Built-in subsystems, opt-in via providers | | Testing | Compose your own harness | `TestApp` with fluent assertions | If your service is a handful of JSON endpoints, plain Hono is a great choice, and because Guren is Hono underneath, growing from one into the other is natural rather than a rewrite. The difference shows up as the app grows: every row in that table is glue code you would otherwise write, test, and maintain yourself. ## Compared with Next.js Next.js and Guren answer different questions. Next.js is React-first: rendering strategy (RSC, streaming, ISR) is the core abstraction, and the backend grows out of the frontend. Guren is server-first: an MVC application in the Laravel tradition, where React is the view layer, delivered through Inertia. In practice this changes how a feature gets built: - **One mental model.** A feature is a route, a controller, a model, and a page. There is no client/server component boundary to reason about, no `'use client'` decisions, and no API route layer between your data and your React props. - **No hand-written data plumbing.** The controller passes typed props straight to the page component. Renaming a database column produces TypeScript errors from the model all the way into the React page. - **The backend is a first-class citizen.** Queues, scheduled jobs, mail, broadcasting, and policies are framework subsystems, not features you assemble from third-party services around a rendering framework. Next.js remains the better fit when server-rendered React itself is the product: heavy content sites, granular per-component streaming, or teams committed to the RSC ecosystem. ## Compared with AdonisJS AdonisJS is the other batteries-included MVC framework in the TypeScript world, and it is excellent. If you want Laravel's architecture on Node.js, it is the established choice. Guren makes two different bets: - **Bun instead of Node.** Benchmarking the same app (the two Inertia-SSR implementations in our [framework comparison](https://github.com/gurenjs/framework-comparison)) measures Guren at **2.3× the throughput on full SSR pages, 3.5× on the JSON path, and 1.8× faster cold starts** ([methodology and one-click reproduction here](https://github.com/gurenjs/framework-comparison/blob/main/BENCHMARK.md)). The app code is held constant, so the gap is the runtime. That is the point: keep the architecture, change the engine. And betting on Bun does not lock your deployment in: first-party plugins target AWS Lambda, Vercel, and Cloudflare Workers, and [guren.dev](https://guren.dev/) itself is a Guren app running on Workers. - **The TypeScript ecosystem's defaults, not first-party rewrites.** AdonisJS ships its own ORM (Lucid), validator (VineJS), and tooling. Guren assembles what the ecosystem already standardized on (Drizzle, Zod, Vite, Inertia) and adds the conventions. Reaching the same spec app left 991 lines across 38 files to maintain on Guren versus 2,438 across 68 on AdonisJS, with 17 direct dependencies versus 43. Typing effort is nearly identical (both scaffold well, at roughly 570 versus 600 handwritten lines for the same app), so the choice comes down to the runtime and whose data layer you want to live with. ## Compared with Laravel and Rails If you come from Laravel or Rails, Guren will feel like home: controllers, models, middleware, policies, resources, jobs, and `make:*` generators all behave the way you expect. What changes is the language boundary — there isn't one: - **One language end to end.** No PHP-to-JavaScript context switch between backend and frontend. Your validation schemas, models, and page props are all TypeScript. - **Types cross the wire.** Laravel's DX with static guarantees: the compiler checks that the props a controller sends match what the React page declares. - **A modern runtime.** Bun executes TypeScript natively: no transpile step in development, fast startup, and a built-in test runner. ## When Not to Choose Guren No framework is the right answer everywhere. Reach for something else when: - **Your product is rendering-centric.** Granular streaming SSR, per-component caching, and the RSC ecosystem are Next.js's home turf. - **You want a micro-footprint service.** A webhook receiver or an edge function does not need MVC. Plain Hono is lighter. - **Your team cannot develop on Bun.** Guren is Bun-first by design: the dev server, test runner, and CLI all assume Bun. Deployment is portable (first-party plugins ship for AWS Lambda, Vercel, and Cloudflare Workers), but if Bun is off the table on developer machines, another framework will fit better. ## Next Steps - [Quickstart](./getting-started.md): scaffold a project and see it running in about five minutes. - [First Steps](./first-steps.md): trace one request through every layer in ten minutes. - [Architecture](./architecture.md): how routing, controllers, models, and Inertia fit together. - [CLI Reference](./cli.md): every command, including the inspection commands agents rely on. --- # Fullstack on Bun Bun ships a runtime, a package manager, a bundler and a test runner, and its dev server can serve HTML pages next to API routes. It does not ship a fullstack framework, and its own documentation says so. This page is for anyone searching for a Bun fullstack framework: what Bun, Hono and Elysia each cover, what is left for you to assemble, and how Guren fills that gap while still deploying to Node.js, Vercel and Cloudflare Workers. ## What Bun Gives You Bun's fullstack dev server (Bun 1.2.3 and later) takes HTML imports as route entrypoints, bundles the scripts and styles they reference, and lets `Bun.serve()` answer API routes from a `routes` object with hot reloading in development. The runtime adds the pieces a server needs on day one: `Bun.serve()`, `bun:sqlite`, `Bun.password`, `Bun.file()`, `bun test` and `bun install`. The same documentation lists what the dev server leaves out. Server-side rendering is not built in, API routes are not auto-discovered, and the feature is marked as a work in progress. Nothing in Bun decides how a project is laid out, how a request reaches a database, or how a user logs in. Those decisions are yours, and so is the glue between them. ## What Hono and Elysia Cover Both are excellent, and both are backend frameworks by their own description. | | Hono | Elysia | |---|---|---| | Describes itself as | A web framework built on Web Standards, for any JavaScript runtime | An ergonomic web framework for building backend servers with Bun | | Ships | Router, middleware, validators, JSX for server-rendered fragments | Router, schema validation, Eden end-to-end types, OpenAPI generation | | Leaves to you | ORM, migrations, auth, sessions, jobs, mail, frontend integration | ORM, migrations, auth, sessions, jobs, mail, frontend integration | If you are building a handful of JSON endpoints, stop here and pick one. Elysia's Eden gives a TypeScript client typed against your routes; Hono runs unchanged on Bun, Node.js, Deno and Workers. ## What Is Left to Build A fullstack application on top of either framework still needs answers to the same questions, and each answer is a dependency to choose plus glue code to write, test and maintain: - Database access and migrations - Passwords, sessions, OAuth, password reset, email verification - Validation that turns into a 422 response with field errors - A frontend that receives typed data from the server without a hand-rolled API layer - Background jobs, mail, cache, events - A test harness that boots the app and asserts on responses - A production build for the target you deploy to ## What Guren Adds Guren is a Laravel-style layer on top of Hono. Every request goes through Hono's router, so you stay in the same performance class, and every row of the previous list has a default: | You need | In a Guren app | |---|---| | HTTP | `router.get('/posts', [PostController, 'index'])`, controllers, middleware groups | | Database | Drizzle ORM with a Model API: `Post.where('published', true).get()`, `bun run db:migrate` | | Auth | `bunx guren add auth` scaffolds registration, login, sessions and the password flows; `bunx guren add oauth` adds providers | | Validation | `this.validateBody(schema)` with a Zod schema; failures become 422 responses | | Frontend | Inertia.js pages in React, with page props typed from the controller by codegen | | Jobs, mail, cache, events | Built-in subsystems, opt-in through providers | | Testing | `TestApp` from `@guren/testing`, on `bun test` | | Coding agents | `guren context`, `guren check` and `guren audit` give an agent a project map and mechanical verification of its work | A route, a controller and a typed page: ```ts // routes/web.ts import { Router } from '@guren/core' import PostController from '@/app/Http/Controllers/PostController' export function registerWebRoutes(router: Router): void { router.get('/posts', [PostController, 'index']) router.post('/posts', [PostController, 'store']) } ``` ```ts // app/Http/Controllers/PostController.ts import { Controller } from '@guren/core' import { Post } from '@/app/Models/Post' import { CreatePostSchema } from '@/app/Http/Validators/PostValidator' import { pages } from '@/.guren/pages.gen' export default class PostController extends Controller { async index() { const posts = await Post.where('published', true).orderBy('createdAt', 'desc').get() return this.inertia(pages.posts.Index, { posts }) } async store() { const data = await this.validateBody(CreatePostSchema) const post = await Post.create(data) return this.redirect(`/posts/${post?.id ?? ''}`) } } ``` The React page for `pages.posts.Index` declares a `Props` interface, and codegen checks the controller's `this.inertia()` call against it. See [First Steps](./first-steps.md) for the whole request path. ## Where Bun Shows Up in a Guren App `bunx create-guren-app my-app` scaffolds a project whose scripts run on Bun: `bun run dev` starts the server under `bun --hot`, `bun test` runs the suite, and the default database is SQLite through `bun:sqlite`, with PostgreSQL and MySQL as the other choices. `Bun.password` is available as the Argon2id hasher when you opt in with `createApp({ auth: { hasher: 'argon2' } })`. Bun-first is not Bun-only. The default password hasher is scrypt through `node:crypto`, so the same code verifies on Node.js. The deploy plugins target AWS Lambda on the Node.js runtime, Vercel on its Bun runtime, and Cloudflare Workers with D1. The [deployment guide](./deployment.md) covers each. ## When to Pick Something Else - A small API service with no database or users: plain Hono or Elysia, and Elysia if you want Eden's typed client. - A content site or storefront where React rendering is the product: Next.js. - A team already on Laravel or Rails with no reason to move: stay. [Why Guren](./why-guren.md) goes through each comparison in more depth. ## Next Steps - [Getting Started](./getting-started.md): scaffold an app and run it. - [The Guren Tutorial](../tutorials/00-overview.md): build a blog with users, authorization, uploads and mail. - [Deployment](./deployment.md): Bun servers, containers, Lambda, Vercel and Workers. --- # Getting Started This guide has two parts. **Part A** gets a fresh Guren app running in about five minutes with SQLite: no Docker, no database server. **Part B** covers the full setup: Postgres or MySQL, environment variables, feature generators, and production builds. Start with Part A; come back to Part B when you need it. The instructions target macOS and Linux, and also work on Windows with WSL2. > [!NOTE] > If any term is unfamiliar, see the [Glossary](./glossary.md). ## Part A: Quickstart (SQLite — no Docker) ### Prerequisites - **Bun 1.4.4**: that is all. ```bash curl -fsSL https://bun.sh/install | bash ``` ### 1. Scaffold a project ```bash bunx create-guren-app my-app cd my-app ``` The scaffolder walks you through a few choices, and the defaults are right for getting started: - **Rendering mode**: SSR (default) or SPA. SSR gives you server-rendered HTML with automatic Vite asset discovery. - **Database**: SQLite (default, zero-config), PostgreSQL, or MySQL. - **AI agents**: which coding agents to set up the [agent harness](./agent-harness.md#choosing-agents) for: Claude Code (default), Codex, Cursor, GitHub Copilot, OpenCode. It then installs dependencies and creates a `.env` file with a generated `APP_KEY` for you. Flags answer the prompts non-interactively (`--mode ssr`, `--db sqlite`, `--agents codex,cursor`), and `--auth` includes authentication scaffolding from the start. To build the command from your choices instead, use [the start page](https://guren.dev/start). It also writes a first prompt for your coding agent. ### 2. Start the dev server ```bash bun run dev ``` This regenerates the typed route/page manifests (codegen) and boots the server. Open `http://localhost:3333`. ### 3. What you should see A crimson ASCII banner in the terminal with the Guren version and URLs, and the welcome page in your browser. The SQLite database file is created on demand at `./data/guren.db`. The fresh app defines no tables yet, so there is nothing to migrate before your first run. ![The welcome page in the browser: a "Welcome to My Blog!" heading above six cards — Routing & Controllers, Eloquent-style ORM, Inertia + React, Auth & Sessions, Queue & Mail, and Zero-config SQLite](../../images/welcome-page.png) > [!TIP] > The dev server spawns Vite automatically for frontend assets, so edits to your React pages appear instantly. Backend changes (controllers, routes, models) are picked up too, without a restart, since the dev server runs under `bun --hot`. Set `GUREN_DEV_VITE=0` to run Vite yourself, `GUREN_VITE_PORT` to start it on another port than 5173, or `GUREN_DEV_BANNER=0` to silence the banner in scripts. ### 4. Explore the project knowledge graph Keep the dev server running and open [http://localhost:3333/_guren/docs](http://localhost:3333/_guren/docs). A fresh app includes a seed architecture decision under `docs/adr/`; the Docs Graph renders it as a document node and will add entity, code-path, and generated-spec relations as your project grows. Click a document to read its frontmatter, trust information, link verdicts, and Markdown body. ![The local Docs Graph viewer: document, spec, and code nodes joined by edges, with concept and relation counts and node-kind filters in the top-left](../../images/docs-graph.png) The viewer is read-only, enabled by `GUREN_DOCS=1` in the scaffold's `dev` script, restricted to your local machine, and never mounted in production. A new app does not include Mermaid, so generated diagrams show as their source until you add it with `bun add -d mermaid`. The [Spec-Anchored Development guide](./spec-anchored.md) explains how to generate spec views and connect decisions to code. ### Add your first feature You have a running app — now build something with it. **[The Guren Tutorial](../tutorials/00-overview.md)** is the recommended next step: a fourteen-chapter course that turns it into a blog, and hands one slice of every chapter to a coding agent. ## Part B: Full Setup Everything below is optional for your first session, but you will want it as your app grows. ### Use PostgreSQL or MySQL Pass `--db postgres` (or `--db mysql`) when scaffolding, or pick it at the prompt. The scaffolder then writes a `docker-compose.yml` for the matching database and points `DATABASE_URL` at it. With **Docker Desktop (Compose v2)** installed, start the database with: ```bash bun run db:up ``` Default connection strings: - PostgreSQL: `postgres://guren:guren@localhost:54322/guren` - MySQL: `mysql://guren:guren@localhost:33306/guren` Stop the container with `bun run db:down` when you are done. > [!TIP] > Already running Postgres locally or in the cloud? Skip Docker entirely and point `DATABASE_URL` at that instance, and the rest of the guide works unchanged. An existing SQLite app can switch later by updating `config/database.ts`; see the [Database Guide](./database.md). ### Environment variables The scaffolder creates `.env` from `.env.example` and fills in a fresh `APP_KEY`. `config/env.ts` declares every variable the app reads and validates them at boot; the [Configuration Guide](./configuration.md) covers it. Key settings: - `APP_URL`: Base URL reported to Inertia (default `http://localhost:3333`). - `DATABASE_URL`: Connection string (a file path for SQLite, a URL for Postgres/MySQL). - `PORT`: HTTP port for the dev server (default `3333`). - `CACHE_STORE`, `QUEUE_CONNECTION`, `MAIL_MAILER`: added by `guren add cache` / `guren add queue` / `guren add mail`, and read by the `config/cache.ts`, `config/queue.ts` and `config/mail.ts` they write. Each value has to name a store that file declares: an unknown `CACHE_STORE`, `QUEUE_CONNECTION` or `MAIL_MAILER` fails the boot. `SESSION_DRIVER` appears once `guren add auth` (or `guren add session`) writes `config/session.ts`, which reads it; until then sessions live in process memory. > [!CAUTION] > Keep `.env` out of version control. If credentials leak in a commit, rotate the database user and regenerate any API keys referenced in the file. ### Add authentication and resources Guren ships with generators that scaffold whole features: ```bash bunx guren add auth bunx guren add resource posts --fields "title:string,body:text,published:boolean" ``` `add auth` sets up registration, login, logout, and session middleware. `add resource` creates a model, migration, controller, validator, resource, and Inertia pages for the given fields. Run `bunx guren add --help` for all available generators (queue, mail, events, storage, and more). ### Generate typed manifests ```bash bun run codegen ``` Codegen writes the typed route helpers and page manifest that power end-to-end type safety. `bun run dev` and `bun run build` run it automatically, so you only need it manually after adding or renaming routes and pages while the server is stopped. ### Run migrations and seed data Once you have added resources (and therefore migrations), apply the schema and populate sample data: ```bash bun run db:migrate && bun run db:seed ``` This works the same for SQLite, Postgres, and MySQL: migrations come from your Drizzle schema in `db/schema.ts`. ### Typecheck and test ```bash bun run typecheck ``` Fix type errors as they appear: catching issues early is much easier than debugging a running app. As you add tests (see the [Testing Guide](./testing.md)), run them with `bun test`. ### Production build When you are ready to ship: ```bash bun run build bun run preview ``` `build` emits hashed client (and, in SSR mode, server) assets under `public/assets/` plus the manifests the runtime reads. `preview` starts the production server locally so you can verify the build. See the [Deployment Guide](./deployment.md) for hosting options. ## Where to go next - **[The Guren Tutorial](../tutorials/00-overview.md)**: the recommended hands-on course for newcomers, a blog with users, authorization, relationships, uploads, mail and agent tools. - **[First Steps](./first-steps.md)**: a ten-minute tour of how one request flows through the framework. Then continue through the guides in this order: 1. [Architecture](./architecture.md) 2. [Routing Guide](./routing.md) 3. [Controller Guide](./controllers.md) 4. [Database Guide](./database.md), then [Models](./models.md) 5. [Frontend Guide](./frontend.md) 6. [Authentication Guide](./authentication.md) 7. [Testing Guide](./testing.md) 8. [Deployment Guide](./deployment.md) Keep the [CLI Reference](./cli.md) handy along the way, and if you spot issues or have ideas, please open an issue or PR. Contributions are welcome. --- # First Steps: A 10-Minute Tour of One Request This tour follows a single request, `GET /posts`, through every layer of a Guren app: route, controller, validation, model, resource, Inertia page, and test. Read it to build a mental map; each stop links to the guide that goes deeper. It assumes a running app (see [Getting Started](./getting-started.md)) with a posts resource generated by: ```bash bunx guren add resource posts --fields "title:string,body:text,published:boolean" ``` Prefer to build this yourself step by step? Take [The Guren Tutorial](../tutorials/00-overview.md) instead: it covers the same ground hands-on, and then keeps going. Here is the whole path first. `GET /posts` moves through these layers in order, and HTML comes back out. ```mermaid flowchart TD Browser["Browser
GET /posts"] Route["1. Route
routes/web.ts"] Controller["2. Controller
PostController.index()"] Validator["3. Validation
ListPostsQuerySchema"] Model["4. Model
Post.paginate()"] Database[("Database
posts table")] Resource["5. Resource
PostResource"] Page["6. Inertia page
posts/Index.tsx"] Browser --> Route --> Controller Controller --> Validator --> Model Model <--> Database Model --> Resource --> Page Page -- "rendered response" --> Browser ``` The rest of this tour walks the stops one at a time. ## 1. The route Every request starts in `routes/web.ts`, where a registrar maps URLs to controller actions: ```ts import { Router } from '@guren/core' import PostController from '@/app/Http/Controllers/PostController' export function registerWebRoutes(router: Router): void { router.get('/posts', [PostController, 'index']) router.post('/posts', [PostController, 'store']) } ``` `GET /posts` matches the first line, so Guren dispatches to `PostController.index`. Groups, middleware, and named routes all live here too (see the [Routing Guide](./routing.md)). ## 2. The controller `app/Http/Controllers/PostController.ts` handles the request: ```ts import { Controller } from '@guren/core' import { Post } from '@/app/Models/Post' import { PostResource } from '@/app/Http/Resources/PostResource' import { ListPostsQuerySchema } from '@/app/Http/Validators/PostValidator' import { pages } from '@/.guren/pages.gen' export default class PostController extends Controller { async index() { const { page } = this.validateQuery(ListPostsQuerySchema) const result = await Post.paginate({ page, perPage: 20 }) return this.inertia(pages.posts.Index, { data: result.data.map((post) => new PostResource(post).toJSON()), }) } } ``` Three things happen: input is validated, data is fetched, and a page is rendered. The [Controller Guide](./controllers.md) covers the full toolbox. ## 3. Validation `this.validateQuery(schema)` parses the query string against a Zod schema and throws a 422 automatically on bad input, with no manual error handling: ```ts import { z } from 'zod' export const ListPostsQuerySchema = z.object({ page: z.coerce.number().int().positive().default(1), }) ``` `validateBody` and `validateParams` work the same way for request bodies and route parameters. See the [Validation Guide](./validation.md). ## 4. The model `app/Models/Post.ts` binds a class to a Drizzle table from `db/schema.ts`: ```ts import { defineModel } from '@guren/core' import { posts } from '@/db/schema' export class Post extends defineModel(posts) {} ``` Queries read like Laravel: `Post.find(1)`, `Post.findOrFail(1)` (throws a 404), `Post.where('published', true).get()`. Column types flow from the schema into every result. See [Models](./models.md). ## 5. The resource `app/Http/Resources/PostResource.ts` decides what leaves the server, so internal columns never leak by accident: ```ts import { Resource } from '@guren/core' export class PostResource extends Resource { toArray() { const { id, title, body, published } = this.resource return { id, title, body, published } } } ``` See the [API Resources Guide](./api-resources.md). ## 6. The Inertia page `this.inertia(pages.posts.Index, props)` renders `resources/js/pages/posts/Index.tsx` — a plain React component that receives the controller's props directly, no API layer in between: ```tsx import type { PageProps } from '@guren/inertia-client/contracts' import { pages } from '@/.guren/pages.gen' type Props = PageProps export default function PostsIndex({ data }: Props) { return (
    {data.map((post) => (
  • {post.title}
  • ))}
) } ``` The index page `bunx guren add resource` generates arrives a little more finished than this: ![The /posts index page: a "Posts" heading with a New Post button, three posts as cards showing title and body excerpt, and page-number pagination below](../../images/posts-index.png) Codegen extracts each page's `Props` into `.guren/pages.gen.ts`, so a controller passing the wrong shape is a compile error. Rename a column and TypeScript flags every layer from schema to browser. See the [Frontend Guide](./frontend.md). ## 7. The test Prove the whole path works with `TestApp`, which drives real requests through your booted app: ```ts import { test } from 'bun:test' import { TestApp } from '@guren/testing' test('lists posts', async () => { const app = await TestApp.create() await app.get('/posts').assertOk() }) ``` See the [Testing Guide](./testing.md) for fluent assertions, `actingAs`, and database helpers. ## 8. Project knowledge The request path explains what the application does; project knowledge records why it works that way and keeps the overview current. `bunx guren spec:generate` derives ER, domain, screen, and module views from the code. ADRs created with `bunx guren make:adr` declare the entities and paths they govern, while `bunx guren check --docs` validates those relations. With `bun run dev` running, open [http://localhost:3333/_guren/docs](http://localhost:3333/_guren/docs) to browse those documents, entities, and code paths as one interactive Docs Graph. The graph surrounds the request path above with its rationale and generated views; it does not replace the route-to-page flow. See [Spec-Anchored Development](./spec-anchored.md) for the full workflow. ![The Docs Graph: spec-view and ADR nodes linked by edges to code nodes such as schema.ts, Models, routes, Controllers, and pages](../../images/docs-graph.png) ## The mental model Every feature in a Guren app follows this same path: - **routes** map URLs to controllers - **validators** parse inputs - **models** describe data access - **resources** shape outputs - **pages** define props - **controllers** compose it all Around that runtime path, **project knowledge** connects generated specs and human decisions back to the code they describe, then checks that the connections remain valid. To add a feature, scaffold the whole path at once and refresh the manifests: ```bash bunx guren add resource comments --fields "body:text,postId:integer" bun run codegen ``` ## Where to go next Ready to build for real? **[The Guren Tutorial](../tutorials/00-overview.md)** walks you through posts, users, authorization, uploads, mail and agent tools hands-on. If any term was unfamiliar, check the [Glossary](./glossary.md). --- # Configuration A Guren app keeps its configuration in `config/`. Two kinds of file live there: - `config/env.ts` declares every environment variable the app reads, with its type and whether it is required. The app validates them once, when it boots. - `config/.ts` files (`database`, `cache`, `mail`, `session`, ...) turn those validated values into service configuration. Each default-exports a *config definition*. Both are plain data. Importing them opens no connection and registers nothing; `createApp()` does that. ```ts // src/app.ts import { createApp } from '@guren/core' import cache from '../config/cache.js' import database from '../config/database.js' import env from '../config/env.js' import http from '../config/http.js' import { registerWebRoutes } from '../routes/web.js' const app = createApp({ env, config: [database, http, cache], routes: registerWebRoutes, }) export default app ``` `create-guren-app` writes this shape, and `guren add cache`, `guren add mail`, `guren add queue`, `guren add storage`, `guren add session` and `guren add oauth` add their definition to the `config` array once `config/env.ts` exists (see [Apps with service providers](#apps-with-service-providers)). ## Declaring the environment `config/env.ts` default-exports a `defineEnv()` schema: ```ts // config/env.ts import { defineEnv, Env, type InferEnv } from '@guren/core' const env = defineEnv({ APP_KEY: Env.string().secret().requiredInProduction() .describe('Root secret for signing and encryption; each use derives its own key.'), APP_URL: Env.url().requiredInProduction(), PORT: Env.port().default(3333), DATABASE_URL: Env.string().optional(), CACHE_STORE: Env.string().default('memory'), LOG_LEVEL: Env.enum(['debug', 'info', 'warn', 'error']).default('info'), }) export default env declare module '@guren/core' { interface AppEnv extends InferEnv {} } ``` The `declare module` block types the validated values everywhere the app reads them: in definitions, in `this.make('env')` from a controller, and in a database connection resolver. ### Types | Builder | Accepts | Value | |---|---|---| | `Env.string()` | anything | `string` | | `Env.url()` | what `new URL()` parses | `string` | | `Env.number()` | a finite number | `number` | | `Env.port()` | an integer from 1 to 65535 | `number` | | `Env.boolean()` | `true`, `false`, `1`, `0` (any case) | `boolean` | | `Env.enum([...])` | one of the listed strings | the union of them | | `Env.custom(schema)` | whatever a synchronous Standard Schema (Zod, Valibot) accepts | the schema's output | ### Presence A variable is required unless it says otherwise: | Modifier | When the variable is unset | |---|---| | (none) | the boot fails | | `.optional()` | the value is `undefined` | | `.default(value)` | the value is `value` | | `.requiredInProduction()` | the boot fails when `NODE_ENV` is `production`; `undefined` elsewhere | **A blank value counts as unset.** `REDIS_URL=` in `.env` reads the same as no line at all, so it takes the default, or fails a required variable. Blank is what a `.env.example` usually ships and what a hosting dashboard leaves behind for a cleared variable. Chain `.allowEmpty()` when an empty string is a real value, such as a mail display name someone chose to leave out. `.secret()` keeps the value out of error messages and makes `guren env:example` write the key blank. `.describe(text)` becomes the comment above the key in `.env.example`. ### When validation fails The boot stops with every problem at once: ```text [guren] Invalid environment (2 problems): APP_KEY required, not set PORT "80a" is not a port ``` ### What you cannot declare `NODE_ENV` and every `GUREN_*` variable stay raw `process.env` reads, and `defineEnv()` throws if you list one. Deploy builds replace the exact expression `process.env.NODE_ENV` at bundle time, which a validated value would bypass, and `GUREN_*` switches (`GUREN_MCP`, `GUREN_DOCS`) are framework gates that must not depend on your schema. ## Config definitions A definition receives the validated env and returns the service's configuration: ```ts // config/cache.ts import { defineCacheConfig } from '@guren/core' import { createRedisClient } from '@guren/core/redis' export default defineCacheConfig((env) => ({ default: env.CACHE_STORE, stores: { memory: { driver: 'memory' }, // A function, so the client is built only when CACHE_STORE selects this store. redis: { driver: 'redis', client: () => createRedisClient({ url: env.REDIS_URL }) }, }, })) ``` | Helper | Binds | Configuration | |---|---|---| | `defineDatabaseConfig(database, { seedOnBoot })` | `database` | connects the ORM at boot, and seeds when `seedOnBoot` is true and migrations exist | | `defineHttpConfig` | (the HTTP kernel) | `hostAuthorization` | | `defineSessionConfig` | `session` | a `SessionConfig` | | `defineCacheConfig` | `cache` | a `CacheConfig` | | `defineMailConfig` | `mail` | a `MailConfig` | | `defineQueueConfig` | `queue` | a `QueueConfig` | | `defineStorageConfig` | `storage` | a `StorageConfig` | | `defineOAuthConfig` | `oauth` | `providers` and an optional `stateStore` | `createApp()` registers a `ConfigServiceProvider` ahead of your providers. In its `register()` it validates the env and binds every definition's manager; in its `boot()` it runs the definitions' boot work (the database connection) before any other provider boots. So a provider can resolve `cache` or `mail` in its own `register()`, and the order of the `config` array does not matter. **A key is configured once.** If a definition and a provider both bind `cache`, the boot fails and names both, rather than one silently winning. When you move a service to a definition, delete its provider. Name checks belong in the definition. A manager accepts any store name and throws on first use, which may be a queued job hours later, so the cache, queue, mail and storage scaffolds check at boot: ```ts // config/queue.ts import { defineQueueConfig, MemoryDriver, SyncDriver } from '@guren/core' const drivers = { sync: () => new SyncDriver(), memory: () => new MemoryDriver(), } export default defineQueueConfig((env) => { if (!Object.hasOwn(drivers, env.QUEUE_CONNECTION)) { throw new Error( `QUEUE_CONNECTION="${env.QUEUE_CONNECTION}" is not a declared driver. Declare it in config/queue.ts or use one of: ${Object.keys(drivers).join(', ')}.`, ) } return { default: env.QUEUE_CONNECTION, drivers } }) ``` Conditional configuration is ordinary code in the callback: ```ts // config/oauth.ts import { defineOAuthConfig, type OAuthProviderConfig, createGitHubOAuthProviderConfig } from '@guren/core' export default defineOAuthConfig((env) => { const providers: Record = {} if (env.OAUTH_GITHUB_CLIENT_ID && env.OAUTH_GITHUB_CLIENT_SECRET && env.OAUTH_GITHUB_REDIRECT_URI) { providers.github = createGitHubOAuthProviderConfig({ clientId: env.OAUTH_GITHUB_CLIENT_ID, clientSecret: env.OAUTH_GITHUB_CLIENT_SECRET, redirectUri: env.OAUTH_GITHUB_REDIRECT_URI, }) } return { providers } }) ``` ### Definitions in a module A [module](./cli.md#application-modules) can keep the definitions for services only it uses in `modules//config/` and list them in its own `defineModule({ config })`, rather than in the app's `createApp({ config })`: ```ts // modules/auth/index.ts import { defineModule } from '@guren/core' import oauth from './config/oauth.js' import { registerAuthRoutes } from './routes' export const authModule = defineModule({ name: 'auth', routes: registerAuthRoutes, config: [oauth], }) ``` The app still has one container, so a module's definition binds the same app-wide key (`oauth` above) that a `createApp({ config })` entry would. `ConfigServiceProvider` binds the app's definitions first, then each module's in `createApp({ modules })` order. A key that the app and a module both define, or that two modules define, fails the boot and names both places. `guren check` reports that collision before you boot, and counts a module's `config` as wiring only while `createApp({ modules })` lists the module. ## The database connection `config/database.ts` keeps its named exports, because `guren db:migrate` and `guren db:seed` import them outside a running app. Its connection resolver receives the validated env when the app boots, and parses the schema itself when the CLI calls it: ```ts // config/database.ts import { createPostgresDatabase, defineDatabaseConfig } from '@guren/core' import env from './env.js' const database = createPostgresDatabase({ migrationsFolder: new URL('../db/migrations', import.meta.url), seedersFolder: new URL('../db/seeders', import.meta.url), connectionString: (context) => (context?.env ?? env.parse(undefined, { mode: 'report' }).values).DATABASE_URL ?? 'postgres://guren:guren@localhost:54322/guren', }) export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase } = database export default defineDatabaseConfig(database, { seedOnBoot: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test', }) ``` `mode: 'report'` returns the values it could validate instead of throwing, so `guren db:migrate` in production does not demand `APP_KEY` just to reach the database. ## Keeping `.env.example` in step `config/env.ts` is the list; `.env.example` should name the same keys. ```bash bunx guren env:example ``` appends every declared key that `.env.example` lacks, with its default (blank for a secret) and its description as a comment. Lines already there are left as you wrote them. ```bash bunx guren check --env ``` fails when the two disagree in either direction, which makes it a CI gate. Plain `guren check` runs the same comparison, and also reports a `config/.ts` that `createApp({ config })` never lists. ## Reading the environment in code Read validated values from the container rather than `process.env`: ```ts import { Controller } from '@guren/core' export default class AdminController extends Controller { async index() { const { ADMIN_EMAIL } = this.make('env') // ... } } ``` In a scaffolded app, the `guren/no-unvalidated-env-read` lint rule reports a `process.env.X` read under `app/`, `config/`, `routes/`, `src/` and `modules/` when `X` is not `NODE_ENV` or a `GUREN_*` variable. `bin/` and `drizzle.config.ts` run before any app exists and are left alone. Where a raw read is deliberate, disable the line and say why: ```ts // oxlint-disable-next-line guren/no-unvalidated-env-read -- CI switch, not app config const secureCookies = process.env.NODE_ENV === 'production' && !process.env.CI ``` ## Cloudflare Workers On Workers, wrangler `vars` and secrets arrive on the entrypoint's `env` argument and are not guaranteed to reach `process.env`. `@guren/plugin-cloudflare` binds that argument before the app boots, and the schema reads a key from it first, then from `process.env`. The same `config/env.ts` works locally and on Workers with no changes. ## Tests `TestApp.fromApp(app)` boots your real `src/app.ts`, definitions included, so a feature test runs against the configuration production uses. To try one variable without touching `process.env`, pass the schema and the overrides to `TestApp.create()`. `envSource` is read ahead of `process.env`, and `''` makes a variable unset: ```ts import { TestApp } from '@guren/testing' import env from '../config/env.js' const app = await TestApp.create({ env, envSource: { CACHE_STORE: 'memory', APP_URL: '' }, providers: [ReportProvider], }) ``` An invalid override makes `create()` reject with an `EnvValidationError`. ## Apps with service providers An app created before config definitions configures services in providers (`CacheProvider`, `MailProvider`, a `SessionProvider` reading `config/session.ts`). Those keep working, and nothing requires moving them. `bunx guren doctor --next` finds them and prints each definition to write, with the values the provider read and the variables to declare. When you move one: 1. Add `config/env.ts` and declare the variables the provider reads. 2. Write `config/.ts` with the matching `define*Config` helper, reading `env` instead of `process.env`. 3. Add it to `createApp({ config })` and delete the provider from `providers`, in the same change. 4. Run `bunx guren env:example` and `bunx guren check`. Once `config/env.ts` exists and no provider binds the key, `guren add ` writes the definition form for the next service you add. --- # Architecture Guren reimagines Laravel's design principles in TypeScript, tying together Bun, Hono, Inertia.js, React, and Drizzle ORM into a full-stack MVC framework. This document outlines the end-to-end flow from routing to response generation and explains the main building blocks. ## High-Level Flow 1. **Container & Providers**: `ServiceProvider` classes register services into the IoC container during boot. 2. **Routing**: Define routes in `routes/web.ts` with a registrar that receives an app-local `Router`. 3. **Controllers**: Extend the `Controller` base class with dependency injection via `static inject`. 4. **Models**: Extend `Model` and link to a Drizzle schema via `static table`. 5. **Views**: Render React components (`resources/js/pages/`) through Inertia.js. 6. **Application boot**: `Application` initialises the container, runs providers, mounts routes, and starts the Bun/Hono server. ## Project Layout ```tree my-app/ ├── app/ │ ├── Http/ │ │ ├── Controllers/ # Home for your controllers │ │ └── Requests/ # Optional legacy `FormRequest` classes for compatibility-heavy apps │ ├── Models/ # Drizzle-backed models extending `Model` │ ├── Providers/ # ServiceProvider classes for registering services │ ├── Events/ # Event classes │ ├── Listeners/ # Event listener classes │ └── Jobs/ # Queue job classes ├── config/ # Application and database configuration files ├── db/ # Schema definitions, migrations, and seeders ├── resources/js/pages/ # React pages rendered via Inertia ├── routes/ # Route declarations (`routes/web.ts`) └── src/ # Application bootstrapping (`src/main.ts`, `src/app.ts`) ``` ## Naming Conventions - Files that export a single class or type (e.g. controllers, models, HTTP application) use `PascalCase.ts` so the filename mirrors the exported identifier. - Utility modules that gather functions or helpers use `kebab-case.ts` (for example `dev-assets.ts`, `inertia-assets.ts`) to distinguish them from class-centric modules. - Each directory sticks to one convention; when you add a new file under `app/Http/Controllers/` or `app/Models/`, prefer PascalCase for new classes, while helper-heavy folders should stay in kebab-case. ## Service Container The IoC container is the heart of Guren's architecture. It manages service registration, resolution, and dependency injection throughout the application lifecycle. ### Binding Services ```ts import { ServiceProvider } from '@guren/core' import { CacheManager } from '@guren/core' export default class CacheProvider extends ServiceProvider { register(): void { this.container.singleton('cache', () => { return new CacheManager({ driver: 'memory' }) }) } boot(): void { // Runs after all providers have registered const cache = this.container.make('cache') cache.initialize() } } ``` ### Resolving Services ```ts // Type-safe resolution const events = container.make('events') const cache = container.make('cache') // Testing: replace a service with a fake container.fake('events', mockEventManager) ``` ### Facades Facades provide a static proxy to services resolved from the container. They offer a convenient, expressive syntax without sacrificing testability: ```ts import { createFacades } from '@guren/core' const { Cache, Events } = createFacades(app.container) // Use anywhere without manually resolving from the container await Cache.get('user:1') await Cache.put('user:1', userData, 3600) Events.dispatch(new UserRegistered(user)) ``` ## Service Providers All providers extend `ServiceProvider` and implement `register()` and optionally `boot()`: ```ts import { ServiceProvider } from '@guren/core' export default class AppServiceProvider extends ServiceProvider { register(): void { // Bind services into the container this.container.singleton('myService', () => new MyService()) } boot(): void { // Runs after ALL providers have called register() // Safe to resolve other services here const db = this.container.make('db') } } ``` - **`register()`**: Bind services into the container. Do not resolve other services here—they may not be registered yet. - **`boot()`**: Called after every provider's `register()` has run. Safe to resolve and use other services. > **Global middleware must be attached in `register()`.** Routes are mounted > *between* `register()` and `boot()`, and Hono only applies middleware > registered ahead of the matched route — `app.use()` from `boot()` never runs > for your routes. Both hooks may be `async` if you need to load resources > (e.g. translation files) first: > > ```ts > export default class I18nProvider extends ServiceProvider { > async register(): Promise { > const i18n = createI18n({ locale: 'ja', fallbackLocale: 'en', path: './lang' }) > await i18n.loadLocales(['en', 'ja']) > this.container.instance('i18n', i18n) > > const app = this.container.make('app') > app.use('*', localeMiddleware) // register(), not boot() > } > } > ``` ### Boot failures and retries Concurrent `app.boot()` calls share one attempt. After a failure, another call retries the failed step and continues, preserving completed boot callbacks, route registrars, route mounting, and dev endpoints. Provider registration and boot hooks that already succeeded are also preserved. `app.booted()` waits for the current attempt when one is running. A rejected hook may have already changed application state or an external service. Guren does not roll back those effects: make the failing hook safe to retry or clean up its partial work. If that is not possible, release any resources it created and construct a fresh application. Retrying does not rerun a successful callback to apply changed options or new routes; use a fresh application for those changes. ## Routing `routes/web.ts` exports a registrar and configures an app-local router: ```ts import { Router, requireAuthenticated } from '@guren/core' import PostController from '@/app/Http/Controllers/PostController' export function registerWebRoutes(baseRouter: Router): void { const router = baseRouter.aliasMiddleware('auth', requireAuthenticated()) router.bind('post', Post) router.get('/', [PostController, 'index']) router.middleware('auth').group((auth) => { auth.get('/posts/:post', [PostController, 'show']) }) } ``` - Each `Application` owns its own router instance, so tests and multiple apps do not share route state. - Controllers are referenced with the `[Class, 'method']` tuple. - Route model binding automatically resolves model instances from route parameters. ## Controllers Controllers extend `Controller` and support dependency injection via `static inject`. Methods return responses through helpers like `this.inertia()`, `this.json()`, `this.created()`, or `this.noContent()`. ```ts import { Controller, paginate, type PaginatedPageProps } from '@guren/core' import { PostResource, type PostResourceData } from '@/app/Http/Resources/PostResource' import { pages } from '@/.guren/pages.gen' type PostsIndexProps = PaginatedPageProps export default class PostController extends Controller { static inject = ['cache'] as const constructor(private cache: CacheManager) { super() } async index() { const result = await Post.where('status', 'published').paginate({ page: 1, perPage: 15 }) const paginator = paginate(result, { path: this.request.path ?? '/posts' }) return this.inertia(pages.posts.Index, { data: result.data.map((post) => new PostResource(post).toJSON()), pagination: { meta: paginator.meta(), links: paginator.links(), }, } satisfies PostsIndexProps) } async store() { const data = await this.validateBody(StorePostSchema) const post = await Post.create(data) return this.created({ post }) } } ``` - `this.ctx`: Full Hono context. - `this.request`: Convenience accessor for the underlying Request. - `this.inertia(component, props, options)`: Creates an Inertia response. - `this.validateBody(schema)`: Validates and returns typed request data. - `await this.input('key')`, `this.query('key')`: Input helpers. ## Models and ORM Models typically use `defineModel(table)` and connect to Drizzle via the table definition itself. The layer provides a fluent QueryBuilder, scopes, hooks, soft deletes, attribute casting, and mass assignment protection. ```ts export type PostRecord = typeof posts.$inferSelect export class Post extends defineModel(posts) { static fillable = ['title', 'content', 'status'] static casts = { metadata: 'json', publishedAt: 'date' } static scopes = { published: (q: QueryBuilder) => q.where('status', 'published'), } static hooks = { creating: async (data) => { data.slug = slugify(data.title) }, } } ``` - Provides Laravel-style helpers like `Model.all()`, `Model.find(id)`, `Model.findOrFail()`, `Model.first()`, and `Model.create(data)`. - Fluent QueryBuilder: `Post.where('status', 'published').orderBy('createdAt', 'desc').limit(10).get()`. - Table inference keeps static helpers strongly typed (e.g. `Post.find()` returns `PostRecord | null`). - Use a provider such as `DatabaseProvider` (which calls `bootModels()`) to invoke `DrizzleAdapter.configure(db)`, making the adapter available to every model. For joins and other queries the builder cannot express, `Model.newQuery().toDrizzle()` hands the query to Drizzle with the model's scopes applied. The Drizzle database instance itself skips the model entirely. ## Inertia.js and Views - Place React pages under `resources/js/pages/` and reference them by component name. - The server embeds the Inertia payload inside HTML via the `data-page` attribute. - The client loads React/Inertia from CDN ESM modules and hydrates the initial page. ## Bootstrapping the Application `src/main.ts` in a generated project illustrates the boot process: 1. Export a route registrar from `routes/web.ts`. 2. Instantiate the application with providers and routes: ```ts const app = createApp({ routes: registerWebRoutes, providers: [DatabaseProvider, AuthProvider, EventServiceProvider], }) ``` 3. `await app.boot()` to mount routes, run provider register/boot hooks, and prepare middleware. 4. `await app.listen()` to start the HTTP server. It resolves to the address it actually bound — `{ port, hostname, url }` — which is not always the port you asked for: `port: 0` lets the OS choose, and outside production a busy port makes it try the next one. Read the port from the return value rather than assuming the requested one: ```ts const { url, port } = await app.listen({ port: 3333 }) console.log(`listening on ${url}`) // the port that is actually bound ``` Pass `portFallback: false` (or set `GUREN_STRICT_PORT=1`) to fail fast on `EADDRINUSE` instead of moving to another port. Both cover the app server's port. The Vite dev server `listen()` starts begins at `GUREN_VITE_PORT` (5173 when unset) and moves on by itself, and the banner names the port it bound; see [Hot Reloading](./frontend.md#hot-reloading). This process runs under Bun as a native module and is triggered by `bun run dev`. ### Stopping the Server `await app.stop()` undoes `listen()`. It closes the socket, takes down the managed Vite dev server that `listen()` started, and detaches the signal handlers it registered: ```ts await app.listen({ port: 3333 }) // ... await app.stop() ``` Stopping waits for in-flight requests to finish. Pass `true` to force them closed instead: ```ts await app.stop(true) // don't wait for in-flight requests ``` That wait is bounded, so a request that never finishes cannot hold shutdown open forever: after 5 seconds `stop()` warns and stops waiting, leaving the remaining connections to drain on their own. The socket has already stopped accepting new connections by then. Set `GUREN_BUN_STOP_TIMEOUT_MS` to change the bound. A `bun --hot` reload is the exception: the server it replaces gets 250 ms (or `GUREN_BUN_STOP_TIMEOUT_MS` when that is shorter), and running out is not reported. That stop is forced, and the reload has already closed every broadcasting socket, so nothing is left to drain. The short bound matters on Bun 1.3.x, where `stop()` never resolves once the server itself has closed a WebSocket: with one broadcasting client connected, each reload took about 5.1 seconds on Bun 1.3.11 and 1.3.14 under the default bound and now takes about 0.3 seconds. On Bun 1.4.2 the same reload takes about 100 ms either way. Calling `stop()` when nothing is listening, or calling it twice, does nothing. A later `listen()` starts cleanly, so you can stop and restart within a single process: ```ts await app.listen({ port: 0 }) await app.stop() await app.listen({ port: 0 }) // a fresh socket ``` `app.address` is `undefined` while stopped, and reports the new address again after a restart. Reach for `stop()` when something other than the process lifetime decides how long the server runs: an app embedded in a larger program, a script that serves and then exits, or a harness that needs a real socket and has to release it. An ordinary deployment does not need it, because `listen()` already tears the server down on `SIGINT`, `SIGTERM`, and process exit — the signals a process manager or container runtime sends. See [Deployment](./deployment.md) for how that fits a production run. ## Database Schema - Drizzle schema definitions live in `db/schema.ts`. - `config/database.ts` provisions tables when the container starts. - Migrations are managed via `bunx guren make:migration` and applied with `bun run db:migrate`. ## Request Lifecycle ```mermaid flowchart LR Hono["1. Hono receives
the request"] Global["2. Global
middleware"] Route["3-4. Route resolved
route middleware
model binding"] Ctrl["5-6. Controller,
database via models"] Inertia["7. this.inertia()"] Client["8. Client
hydrates"] Hono --> Global --> Route --> Ctrl --> Inertia --> Client ``` 1. Hono receives an HTTP request. 2. Global middleware runs (session, CSRF, rate limiting, etc.). 3. The application router resolves the matching handler and runs route-level middleware. 4. Route model binding resolves any bound parameters. 5. The controller is instantiated with injected dependencies. 6. The controller method executes, using models to access the database. 7. `this.inertia()` hands data to the view and builds the Inertia response. 8. The client hydrates React on the first load; subsequent navigation stays within Inertia-powered SPA transitions. For a deeper dive into internals, explore the [CLI Reference](./cli.md) and the inline documentation within your generated project. --- # Routing Routes map a method and a URL to the code that answers it: a controller action or an inline handler. Each application owns one `Router`. A route file exports a registrar, a function that receives that router and registers routes on it, and `src/app.ts` passes the registrar to `createApp()`. A route can also carry a contract, the schemas and metadata that validation, codegen and agent tools read. [Route Contracts](./route-contracts.md) explains how to write one, and [OpenAPI](./openapi.md) covers the document generated from them. ## Defining Routes A scaffolded app's `routes/web.ts` already exports a registrar, `registerWebRoutes`. Add routes inside it: ```ts // routes/web.ts import { Router } from '@guren/core' import PostsController from '@/app/Http/Controllers/PostsController' export function registerWebRoutes(router: Router): void { // Controller tuple — the most common pattern router.get('/posts', [PostsController, 'index']) router.post('/posts', [PostsController, 'store']) router.put('/posts/:id', [PostsController, 'update']) router.delete('/posts/:id', [PostsController, 'destroy']) // Inline handler — great for lightweight endpoints router.get('/health', (ctx) => ctx.json({ status: 'ok' })) } ``` Available methods: `router.get`, `router.post`, `router.put`, `router.patch`, `router.delete`, `router.query` (see [The QUERY Method](#the-query-method)), and the generic `router.on(method, path, handler)`. `src/app.ts` passes the registrar to `createApp()`. The scaffold's file passes more options than this; only `routes` matters here: ```ts // src/app.ts import { createApp } from '@guren/core' import { registerWebRoutes } from '@/routes/web' const app = createApp({ routes: registerWebRoutes, }) export default app ``` ## Route Parameters Dynamic segments use `:param` syntax: ```ts router.get('/posts/:id', [PostsController, 'show']) router.get('/users/:userId/posts/:postId', [PostsController, 'showForUser']) ``` Read them in the controller: ```ts const id = this.ctx.req.param('id') const userId = this.ctx.req.param('userId') ``` Hono's pattern syntax applies: | Pattern | Matches | |---------|---------| | `/posts/:id?` | `/posts` and `/posts/42` (optional segment) | | `/items/:id{[0-9]+}` | `/items/42`, not `/items/abc` (regex constraint) | | `/files/:path{.+}` | `/files/a/b/c` (several segments) | Avoid `/:slug*`. It is not a Hono wildcard: it registers a one-segment parameter literally named `slug*`, so `/files/x/y` returns 404. > [!NOTE] > For large apps, split routes into multiple registrars (`routes/api.ts`, `routes/admin.ts`) and compose them from `src/app.ts`. ## Route Groups Group routes under a shared prefix to avoid repetition: ```ts export function registerWebRoutes(router: Router): void { router.group('/posts', (posts) => { posts.get('/', [PostsController, 'index']) // GET /posts posts.get('/:id', [PostsController, 'show']) // GET /posts/:id posts.post('/', [PostsController, 'store']) // POST /posts }) } ``` Groups nest naturally. Prefixes combine automatically: ```ts router.group('/admin', (admin) => { admin.group('/users', (users) => { users.get('/', [AdminUsersController, 'index']) // GET /admin/users }) }) ``` ## Named Routes Give routes a name, then generate URLs by name instead of hardcoding paths: ```ts router.get('/posts/:id', [PostsController, 'show']).name('posts.show') // Later, generate the URL const url = router.route('posts.show', { id: 42 }) // => '/posts/42' ``` This keeps your code resilient to path changes. If you rename `/posts` to `/articles`, only the route definition changes. ## Middleware Attach middleware to a route with `.middleware()`, or to a set of routes with `router.middleware().group()`. Names you register with `aliasMiddleware()` can be used in place of functions. The [Middleware guide](./middleware.md) covers groups, execution order and the built-in middleware. ### Registering Aliases Give middleware functions short names so you can reference them as strings: ```ts import { Router, requireAuthenticated } from '@guren/core' import { requireAdmin } from '@/app/Http/middleware/admin' export function registerWebRoutes(baseRouter: Router): void { const router = baseRouter .aliasMiddleware('auth', requireAuthenticated()) .aliasMiddleware('admin', requireAdmin()) router.get('/admin', [AdminController, 'index']).middleware('auth', 'admin') router.middleware('auth').group((auth) => { auth.get('/dashboard', [DashboardController, 'index']) auth.get('/settings', [SettingsController, 'index']) }) } ``` > [!IMPORTANT] > `aliasMiddleware()` returns a **new `Router` type** carrying the alias name it just registered. Call it without capturing the result and the name never reaches the type, so a later `.middleware('auth')` fails to compile. Always chain and assign, as above. > > The type travels across functions too. A registrar typed `Router<'auth' | 'guest'>` only accepts a router on which both names were aliased and the result captured, so hand it the captured `router` rather than the `baseRouter` it came from. The entry registrar itself takes plain `Router`: it is the one that registers the aliases, and `createApp({ routes })` hands it a router carrying none. ## Route Contracts The second argument of a route method can be an options object holding Zod schemas for `params`, `query`, `body` and `output`, plus `name`, `bind` and `agent` metadata. Requests are validated against those schemas before the action runs, and codegen, the OpenAPI document and agent tools are built from the same definitions: ```ts router.post('/posts', { body: CreatePostSchema, name: 'posts.store' }, [PostsController, 'store']) ``` [Route Contracts](./route-contracts.md) describes each field. The `bind` map is described under [Route Model Binding](#route-model-binding) below. ## Route Model Binding Without model binding, every controller method starts with the same boilerplate: ```ts // Before: manual lookup in every method async show() { const post = await Post.findOrFail(this.ctx.req.param('id')) return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } ``` With model binding, Guren resolves the model automatically. Declare the binding with the `bind` field of the route's options (see [Route Contracts](#route-contracts)) and read the record in the controller with `this.model()`: ```ts // routes/web.ts — :id is looked up with Post.findOrFail(id) router.get('/posts/:id', { bind: { id: Post }, name: 'posts.show' }, [PostsController, 'show']) // Controller receives the resolved model — no lookup needed async show() { const post = this.model(Post) // typed as PostRecord return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } ``` If the record is not found, a 404 is returned automatically. ### Binding by another column The class alone always looks up by primary key. To resolve a slug (or any other unique column), bind a `[Model, column]` tuple. The router calls `Post.findOrFail(value, 'slug')` and `this.model(Post)` returns the same record: ```ts router.get('/posts/:slug', { bind: { slug: [Post, 'slug'] }, name: 'posts.show' }, [PostsController, 'show']) async show() { const post = this.model(Post) // resolved by slug // ... } ``` The column name is a plain string: a misspelled column fails the query rather than returning 404, so keep it aligned with your schema. When the same parameter is bound both on the router (below) and on the route, the route's own `bind` wins and the record is looked up once. ### Router-level bindings `router.bind(param, ...)` binds a parameter name once for every controller-action route on that router whose path contains it. It accepts the same model forms as the `bind` option (`Post` or `[Post, 'slug']`), plus a custom resolver function: ```ts router.bind('post', Post) // by primary key router.bind('post', [Post, 'slug']) // by slug router.bind('post', async (value) => Post.where('slug', value).firstOrFail()) // custom resolver router.get('/posts/:post', [PostsController, 'show']) ``` Router-level bindings reach the controller as **positional arguments after the context**, in path-parameter order. A model binding (`Post` or `[Post, 'slug']`) is also available through `this.model(Post)`; a custom resolver's value is only available positionally, since there is no model class to look it up by: ```ts import type { Context } from '@guren/core' async show(_ctx: Context, post: PostRecord) { return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } ``` > [!NOTE] > Bound values are not stored on the Hono context — `this.ctx.get('post')` returns `undefined`. Use `this.model(Post)` or the positional argument. Bindings resolve for controller-action routes only; an inline handler receives Hono's `(ctx, next)` and has to look the record up itself. ## Resource Routes `router.resource()` generates a full set of RESTful routes from a single line: ```ts router.resource('/posts', PostsController) ``` This registers: | Method | Path | Action | Name | |--------|------|--------|------| | GET | `/posts` | `index` | `posts.index` | | GET | `/posts/create` | `create` | `posts.create` | | POST | `/posts` | `store` | `posts.store` | | GET | `/posts/:id` | `show` | `posts.show` | | GET | `/posts/:id/edit` | `edit` | `posts.edit` | | PUT | `/posts/:id` | `update` | `posts.update` | | DELETE | `/posts/:id` | `destroy` | `posts.destroy` | Only methods that exist on the controller are registered. Scope the routes with options: ```ts // API-only — skip create/edit (those are for HTML forms) router.resource('/posts', PostsController, { only: ['index', 'show', 'store', 'update', 'destroy'], }) // Custom parameter name router.resource('/posts', PostsController, { param: 'post' }) ``` ## The QUERY Method `router.query()` registers a route for the HTTP QUERY method ([RFC 10008](https://www.rfc-editor.org/info/rfc10008/)): safe and idempotent like GET, but the request carries a body like POST. Use it for search and filter endpoints whose criteria are too complex for a URL: ```ts import { z } from 'zod' router.query('/posts/search', { name: 'posts.search', body: z.object({ keywords: z.array(z.string()), limit: z.number().default(20) }), }, [PostsController, 'search']) ``` Things to know before reaching for it: - **Handlers must not mutate state.** QUERY is a safe method, so Guren's CSRF protection skips it. That is sound because browsers cannot send QUERY cross-site without a CORS preflight, but only while the handler really is read-only. To require CSRF tokens anyway, add `'QUERY'` to the CSRF middleware's `methods` option. - **Call it with `fetch` or the generated API client** (`client.request('posts.search', { body })`). HTML forms and Inertia form helpers cannot send QUERY. - **Check your deployment path.** Guren's fetch-based adapters (Bun, the Cloudflare Workers and Vercel plugins) do not block QUERY, but verify that your platform's ingress accepts it: some proxies and CDNs reject methods outside the classic set. Notably CloudFront, which the Lambda plugin's asset distribution puts in front of your app, does not forward QUERY. Intermediary caching of QUERY responses is also not widely implemented yet. - **OpenAPI 3.1 cannot express QUERY**, so `guren openapi:generate` skips QUERY routes with a warning. - To advertise support to clients, set the `Accept-Query` response header yourself, e.g. `ctx.header('Accept-Query', 'application/json')` on the resource's GET handler. --- # Route Contracts A route contract is the options object you pass as the second argument when you register a route. Its schemas validate the request before the action runs, and the same definitions type the generated route helpers and API client, feed the [OpenAPI document](./openapi.md) and describe the route's agent tool. Registering the route itself (paths, groups, names, middleware, model binding) is covered in [Routing](./routing.md). ## Declaring a Contract Put the options object between the path and the handler. Write its schemas with the zod 4 API (`import { z } from 'zod'`). Schemas authored with the zod v3 API are refused by the structural tools with a warning (see [Validation](./validation.md)). ```ts import { z } from 'zod' const CreatePostSchema = z.object({ title: z.string().min(1), body: z.string().min(1), }) const PostIdParams = z.object({ id: z.coerce.number().int().positive(), }) router.post('/posts', { body: CreatePostSchema, name: 'posts.store', }, [PostsController, 'store']) router.get('/posts/:id', { params: PostIdParams, name: 'posts.show', }, [PostsController, 'show']) ``` Available contract fields: | Field | Purpose | |-------|---------| | `name` | Route name for URL generation and codegen | | `params` | Zod schema for path parameters | | `query` | Zod schema for query string parameters | | `body` | Zod schema for the request body | | `output` | Zod schema for the response body — validated on 2xx answers only, so error responses and redirects pass through as the application wrote them | | `resource` | Resource class response hint — types the API client without a schema | | `bind` | [Route model binding](./routing.md#route-model-binding) map — `{ id: Post }` (primary key) or `{ slug: [Post, 'slug'] }` (another column) | | `middlewares` | Array of middleware handlers | > [!NOTE] > Repeated query keys reach the `query` schema as arrays (`?tag=a&tag=b` → `{ tag: ['a', 'b'] }`), while a key that appears once stays a string. See [Array-Style Query Parameters](./validation.md#array-style-query-parameters). ## Reading Validated Input The `params`, `query` and `body` schemas are checked before the handler runs, for a controller action as much as for an inline handler. A request that fails one gets a 422 and the action never runs; on an Inertia request the errors are flashed back to the form, keyed by field path as `validateBody()` keys them. The action reads what the schemas parsed with `this.validated()`, passing its own route name: ```ts import type { UserRecord } from '@/app/Models/User' export default class PostsController extends Controller { async store() { const { body } = this.validated('posts.store') const user = await this.auth.userOrFail() const post = await Post.create(body, { set: { authorId: user.id } }) return this.redirect(`/posts/${post.id}`) } } ``` - Values arrive after coercion, defaults and transforms, so a `z.coerce.number()` param is a `number`. A segment the route declares no schema for is `undefined`. - A field ending in `.transform()` is typed `unknown`, since codegen cannot read what the function returns. Follow it with a schema to type it: `z.string().transform(Number).pipe(z.number())` is a `number`. - Once `guren codegen` has generated the route types, the route name is checked at compile time and the result is typed from the contract. A name other than the route being served throws at runtime. - An action mounted on several routes, such as a PUT and a PATCH, passes every name: `this.validated(['posts.update', 'posts.patch'])`. - The contract runs before the action, so an invalid body gets its 422 before a check inside the action (such as `this.auth.userOrFail()`) runs. When an unauthenticated request must get a 401 first, put the check in route middleware. A route that declares no contract still validates with `validateBody()`, `validateQuery()` and `validateParams()` (see [Validation](./validation.md)). ## Resource Response Hints Routes that answer with [API Resources](./api-resources.md) already have a response type: the one codegen extracts from the Resource class into `.guren/data.gen.ts`. Writing an `output` schema for such a route would restate that shape in Zod and leave two copies to drift. Declare the Resource itself instead: ```ts import { PostResource } from '@/app/Http/Resources/PostResource' router.get('/api/posts', { name: 'posts.index', resource: { data: [PostResource] }, }, [PostsController, 'index']) ``` The hint mirrors the JSON the controller builds: a bare class (`resource: PostResource`) for a single resource, a one-element array (`resource: [PostResource]`) for a collection, and a plain object for an envelope, where `{ data: [PostResource] }` matches `this.json({ data: PostResource.collection(posts) })`. Nesting works to any depth. `guren codegen` resolves each class against `app/Http/Resources` (at the project root and inside every `modules//`) and types the generated API client's `json()` with the assembled shape (`{ data: Data.Post[] }` here). | | `output` schema | `resource` hint | |---|---|---| | Checked at request time | Yes, on 2xx responses | No | | Types the API client | Yes | Yes | | Appears in the OpenAPI document | Yes | No (`openapi:generate` warns) | | When both are set | Wins | Ignored | If the hint names a Resource class codegen cannot find, codegen warns and leaves the response untyped. > [!NOTE] > Every leaf of the hint must be a Resource class. An envelope that mixes Resources with plain typed objects (a paginated response's `meta` and `links`, for example) cannot be expressed yet; bind an `output` schema for those routes instead. ## Agent Tools A named route can be exposed to AI agents as an MCP tool by declaring `agent` metadata on it. Everything about the tool (its input schema, its output schema, its authorization) is derived from the contracts above; nothing is restated. ```ts // Fluent router .post('/posts', { body: CreatePostSchema, output: PostResponseSchema }, [PostsController, 'store']) .name('posts.store') .agent({ description: 'Create a blog post as the authenticated user.' }) // Or as a contract key router.post('/posts', { name: 'posts.store', body: CreatePostSchema, agent: { description: 'Create a blog post as the authenticated user.' }, }, [PostsController, 'store']) ``` `resource()` takes the same metadata per action, and **an action not listed is not exposed**: ```ts router.resource('/posts', PostsController, { agent: { index: { description: 'List posts.' }, show: { description: 'Fetch one post by id.' }, }, }) ``` Exposure is opt-in per route, the tool name is the route name used verbatim, and a route with no `.name()` cannot become a tool. Declaring `agent` in the route options *and* chaining `.agent()` throws — declare it once. `bunx guren tool:list` shows what an agent would see. For the metadata fields, the input/output derivation rules and the MCP endpoint, see the [Agent Interface guide](./agent-interface.md); for token scopes, approvals and the audit trail, see [Control and Audit Agent Tool Access](./agent-tool-governance.md). --- # Controllers Controllers are where your application logic lives. They receive HTTP requests, interact with models and services, and return responses. Think of them as the glue between what the user asks for and what your app delivers. ## Your First Controller Generate a controller with the CLI, then add a couple of methods: ```bash bunx guren make:controller PostsController ``` ```ts // app/Http/Controllers/PostsController.ts import { Controller, paginate, type PaginatedPageProps } from '@guren/core' import { Post } from '@/app/Models/Post' import { PostResource, type PostResourceData } from '@/app/Http/Resources/PostResource' import { ListPostsQuerySchema, PostIdParamSchema } from '@/app/Http/Validators/PostValidator' import { pages } from '@/.guren/pages.gen' type PostsIndexProps = PaginatedPageProps export default class PostsController extends Controller { async index() { const { page } = this.validateQuery(ListPostsQuerySchema) const result = await Post.paginate({ page, perPage: 10, orderBy: ['id', 'desc'] }) const paginator = paginate(result, { path: this.request.path ?? '/posts' }) return this.inertia(pages.posts.Index, { data: result.data.map((post) => new PostResource(post).toJSON()), pagination: { meta: paginator.meta(), links: paginator.links(), }, } satisfies PostsIndexProps) } async show() { const { id } = this.validateParams(PostIdParamSchema) const post = await Post.findOrFail(id) return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } } ``` Wire it up in `routes/web.ts`: ```ts import { Router } from '@guren/core' import PostsController from '@/app/Http/Controllers/PostsController' export function registerWebRoutes(router: Router): void { router.get('/posts', [PostsController, 'index']) router.get('/posts/:id', [PostsController, 'show']) } ``` That is all it takes. The `[Controller, 'method']` tuple tells Guren which class to instantiate and which method to call for each request. ## Responding to Requests Controllers provide helpers for every common response type: ```ts export default class PostsController extends Controller { async index() { const posts = await Post.all() return this.json(posts) // 200 JSON } async show() { const { id } = this.validateParams(PostIdParamSchema) const post = await Post.findOrFail(id) return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) // Inertia page } async store() { const data = await this.validateBody(StorePostSchema) const post = await Post.create(data) return this.created({ post: new PostResource(post).toJSON() }) // 201 JSON } async update() { await Post.update({ id: 1 }, { title: 'Updated' }) return this.redirect('/posts') // 302 redirect } async destroy() { await Post.delete({ id: 1 }) return this.noContent() // 204 empty } } ``` | Helper | Status | Description | |--------|--------|-------------| | `this.json(data)` | 200 | Return JSON | | `this.inertia(component, props)` | 200 | Render an Inertia page | | `this.view(component, props)` | 200 | Render a server-rendered HTML page ([Server-Rendered Views](./views.md)) | | `this.created(data)` | 201 | JSON with 201 status | | `this.accepted(data)` | 202 | JSON with 202 status | | `this.redirect(url)` | 302 | HTTP redirect | | `this.noContent()` | 204 | Empty response | `this.inertia()` sets the Inertia page `url` to the request path including the query string (e.g. `/posts?page=2`), which is what `usePage().url` returns on the client. Pass the `url` option only when you need to override it. ## Reading Input Controllers parse both JSON and form-encoded bodies automatically: ```ts async store() { // Read a single field const title = await this.input('title') // Query parameters (synchronous) const page = this.query('page', '1') // Canonical schema-first body parsing const data = await this.validateBody(StorePostSchema) // Check if a field exists if (await this.has('email')) { // ... } } ``` > [!TIP] > Body-reading methods (`input`, `has`, `validateBody`) are `async` because they parse the request body. The `query` method reads URL parameters and is synchronous. ## Writes in a GET Action A GET route answers more than page views. A `HEAD` request (uptime monitors, link checkers, crawlers) runs the GET route's action and drops the body, and an Inertia prefetch (``) requests the page when a pointer hovers over the link. A write in such an action, like a view counter or a last-viewed timestamp, then counts requests nobody saw. Guard the write on the request itself: ```ts async show() { const post = this.model(Post) const prefetch = this.request.header('Purpose') === 'prefetch' if (this.request.method === 'GET' && !prefetch) { await Post.forceUpdate({ id: post.id }, { lastViewedAt: new Date() }) } return this.inertia(pages.posts.Show, { post }) } ``` `this.request.method` reads `HEAD` for a HEAD request, although the action that runs is the GET route's. In a test, `http.head('/posts/1')` sends one (see [Testing](./testing.md#testapp)). ## Validation ### Route Contracts (Recommended) When the route declares `params`, `query` or `body` schemas, the framework validates the request before the action runs and answers 422 on failure. The action reads the parsed values instead of validating again: ```ts // routes/web.ts router.post('/posts', { name: 'posts.store', body: StorePostSchema }, [PostsController, 'store']) // app/Http/Controllers/PostsController.ts export default class PostsController extends Controller { async store() { const { body } = this.validated('posts.store') // already validated const post = await Post.create(body) return this.redirect(`/posts/${post.id}`) } } ``` `this.validated(routeName)` returns `{ params, query, body }` as the schemas parsed them, typed from the route contract once `guren codegen` has run. See [Reading Validated Input](./route-contracts.md#reading-validated-input) for the details. ### Zod Schema Helpers For a route without a contract, use `validateBody`, `validateQuery`, and `validateParams` with Zod schemas directly in your controller. They accept any object with a `safeParse()` method (Zod, Valibot, etc.) and throw a `ValidationException` (422) on failure: ```ts import { Controller } from '@guren/core' import { z } from 'zod' import { Post } from '@/app/Models/Post' import type { UserRecord } from '@/app/Models/User' const PostIdParamSchema = z.object({ id: z.coerce.number().int().positive() }) const StorePostSchema = z.object({ title: z.string().min(1), content: z.string().min(10) }) const PageQuerySchema = z.object({ page: z.coerce.number().int().min(1).default(1) }) export default class PostsController extends Controller { async index() { const { page } = this.validateQuery(PageQuerySchema) // throws 422 const result = await Post.paginate({ page, perPage: 10 }) const paginator = paginate(result, { path: this.request.path ?? '/posts' }) return this.inertia(pages.posts.Index, { data: result.data.map((post) => new PostResource(post).toJSON()), pagination: { meta: paginator.meta(), links: paginator.links(), }, }) } async show() { const { id } = this.validateParams(PostIdParamSchema) // throws 422 const post = await Post.findOrFail(id) // throws 404 return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } async store() { const data = await this.validateBody(StorePostSchema) // throws 422 const user = await this.auth.userOrFail() // throws 401 const post = await Post.create(data, { set: { authorId: user.id } }) return this.redirect('/posts') } } ``` | Helper | Input Source | Async | |--------|-------------|-------| | `this.validateBody(schema)` | Request body (JSON / form) | Yes | | `this.validateQuery(schema)` | URL query parameters | No | | `this.validateParams(schema)` | Route parameters (`:id`, etc.) | No | All three throw `ValidationException` (HTTP 422) on failure, which the `ExceptionHandler` renders automatically. ## Dependency Injection When your controller needs services (caching, events, mail), declare them with `static inject` and Guren resolves them from the container: ```ts import { Controller } from '@guren/core' import type { CacheManager, EventManager } from '@guren/core' import { Post } from '@/app/Models/Post' export default class PostsController extends Controller { static inject = ['cache', 'events'] as const constructor( private cache: CacheManager, private events: EventManager, ) { super() } async index() { const cached = await this.cache.get('posts:all') if (cached) return this.json(cached) const posts = await Post.all() await this.cache.put('posts:all', posts, 300) return this.json(posts) } } ``` The `as const` assertion on `inject` ensures type safety. Each string maps to a key registered in the service container. ## Resource Controllers Instead of defining seven routes by hand, use `router.resource()`: ```ts router.resource('/posts', PostsController) ``` This generates: | Method | Path | Controller Method | |--------|------|-------------------| | GET | `/posts` | `index` | | GET | `/posts/create` | `create` | | POST | `/posts` | `store` | | GET | `/posts/:id` | `show` | | GET | `/posts/:id/edit` | `edit` | | PUT | `/posts/:id` | `update` | | DELETE | `/posts/:id` | `destroy` | Only methods that exist on your controller are registered. Limit the routes with `only` or `except`: ```ts router.resource('/posts', PostsController, { only: ['index', 'show'] }) ``` ## Sharing Data Between Methods Controllers are instantiated per request, so one method can set an instance field for a helper method to reuse. For data every page needs (the signed-in user, for example), reach for Inertia shared props or middleware instead. ## Inertia Shared Props Use `shareInertiaProps()` to inject application-wide data into every Inertia response. The natural home for the call is a service provider's `boot()` (generate one with `bunx guren make:provider`). ```ts // app/Providers/AppInfoProvider.ts import { ServiceProvider, shareInertiaProps } from '@guren/core' export default class AppInfoProvider extends ServiceProvider { boot(): void { shareInertiaProps(() => ({ appVersion: process.env.APP_VERSION || 'dev', }), this.container) } } ``` > [!NOTE] > The request locale and translation catalogs are already shared for you when the app is created with `createApp({ i18n })` — see the [i18n guide](./i18n.md). There's no need to hand-roll locale detection here. It merges its props over whatever resolver was registered before, so several providers can each contribute shared props without clobbering one another. Passing `this.container` scopes the props to that one application. Omit it and the props are process-wide, so a second application booted in the same process (a test suite, a warm serverless instance) receives them too. > [!NOTE] > Sharing the signed-in user (`auth.user`) is already registered for you by the `AuthProvider` that `bunx guren add auth` generates — there's no need to register it again. See the [Authentication guide](./authentication.md) for details. Augment the exported `InertiaSharedProps` interface to keep these props typed across controllers and React pages: ```ts // types/inertia.d.ts import type { UserRecord } from '@/app/Models/User' declare module '@guren/core' { interface InertiaSharedProps { auth: { user: UserRecord | null } } } ``` When you need the component's prop type, `InferInertiaProps>` gives you both the action props and the shared props. ## Testing Controllers `TestApp` boots a lightweight instance of your app for expressive HTTP testing: ```ts import { TestApp } from '@guren/testing' const app = await TestApp.create() // Basic request assertions await app.get('/posts').assertOk() await app.post('/posts', { title: 'New' }).assertStatus(201) // Authenticated requests await app.actingAs(user).get('/dashboard').assertOk() // JSON structure assertions await app.get('/api/posts') .assertOk() .assertJsonCount(5, 'data') .assertJsonPath('data.0.title', 'Hello') ``` > [!TIP] > Controllers stay thin when they delegate business logic to models or services. Treat them as an orchestration layer that glues your app together. --- # Middleware Guide Middleware runs code around a request: before the controller action, after it, or instead of it. Guren uses Hono's middleware model, and you attach middleware in one of three places: | Where | Applies to | Section | |-------|------------|---------| | The application, with `app.use()` | Every request | [Global Middleware](#global-middleware) | | A route or route group, with `.middleware()` | Those routes | [Route Middleware](#route-middleware) | | A name, with `aliasMiddleware()` / `groupMiddleware()` | Routes that use the name | [Middleware Aliases](#middleware-aliases), [Middleware Groups](#middleware-groups) | An app created with `createApp({ auth })` already mounts the session and CSRF middleware, and every app mounts the auth context (which `requireAuthenticated` reads); see [Built-in Helpers](#built-in-helpers). ## Global Middleware ```ts // src/app.ts import { createApp, defineMiddleware } from '@guren/core' const requestTimer = defineMiddleware(async (ctx, next) => { const started = performance.now() await next() const duration = Math.round(performance.now() - started) console.log(`${ctx.req.method} ${ctx.req.path} -> ${ctx.res.status} (${duration}ms)`) }) const app = createApp() app.use('*', requestTimer) ``` Global middleware has to be attached before the routes are mounted. A service provider therefore calls `app.use()` from `register()`, not `boot()`: routes are mounted between the two, and middleware added in `boot()` never runs for them. [Architecture](./architecture.md#service-providers) shows the provider form. ## Route Middleware ```ts import { Router, requireAuthenticated } from '@guren/core' import DashboardController from '@/app/Http/Controllers/DashboardController' export function registerWebRoutes(router: Router): void { router.get('/dashboard', [DashboardController, 'index']).middleware( requireAuthenticated({ redirectTo: '/login' }), ) } ``` Route middleware applies only to that route, or to every route inside a group. `.middleware()` accepts handler functions, registered alias names, or a mix of both. Mixing the two changes the order they run in; see [Execution Order](#execution-order). ## Middleware Aliases Register a short name for a middleware function, then refer to it by name in your route files without importing the function each time. `requireAdmin` here is middleware the app defines itself (see [Writing Custom Middleware](#writing-custom-middleware)): ```ts import { Router, requireAuthenticated } from '@guren/core' import { requireAdmin } from '@/app/Http/middleware/admin' export function registerWebRoutes(baseRouter: Router): void { const router = baseRouter .aliasMiddleware('auth', requireAuthenticated()) .aliasMiddleware('admin', requireAdmin()) } ``` > [!IMPORTANT] > `aliasMiddleware()` returns a **new `Router` type** carrying the alias name it just registered. Call it without capturing the result and the name never reaches the type, so a later `.middleware('auth')` fails to compile. Always chain and assign, as above. > > The type also travels across functions. See [Registering Aliases](./routing.md#registering-aliases). Once registered, use the alias anywhere middleware is accepted: ```ts router.get('/dashboard', [DashboardController, 'index']).middleware('auth') router.post('/settings', [SettingsController, 'update']).middleware('auth', 'admin') ``` Aliases also make middleware visible to `guren audit`, which reports a route's middleware by name. It recognizes the framework's guards and authorization middleware either way, but your own middleware passed as a bare function is invisible to it. ## Middleware Groups A group bundles several aliases under one name, for stacks that run together. Every member must be a registered alias or another group: ```ts const router = baseRouter .aliasMiddleware('auth', requireAuthenticated()) .aliasMiddleware('admin', requireAdmin()) .aliasMiddleware('throttle', createRateLimitMiddleware({ limit: 60, windowMs: 60_000 })) .groupMiddleware('backoffice', ['auth', 'admin']) .groupMiddleware('api', ['throttle']) ``` Apply a group to a set of routes with `router.middleware()`: ```ts router.middleware('backoffice').group((backoffice) => { backoffice.get('/admin', [AdminController, 'index']) backoffice.get('/admin/users', [AdminUserController, 'index']) }) router.middleware('api').group((api) => { api.get('/api/posts', [ApiPostController, 'index']) api.post('/api/posts', [ApiPostController, 'store']) }) ``` Groups and individual aliases combine: ```ts router.middleware('api', 'auth').group((group) => { group.get('/api/me', [ProfileController, 'show']) group.put('/api/me', [ProfileController, 'update']) }) ``` ## Execution Order A route's middleware runs in this order: 1. Every alias or group name in the route's chain, outer groups first. 2. Every inline handler function, outer groups first. 3. Validation of the route's `body`, `params` and `query` schemas. 4. The controller action. Names run before functions across groups as well as within one `.middleware()` call. So an inline handler on an outer group runs *after* a name on an inner group, the reverse of how the code reads: ```mermaid flowchart LR subgraph Written["As written"] direction TB W1["outer group
.middleware(inlineA)"] W2["inner group
.middleware('auth')"] W3["route
.middleware(inlineB)"] W1 --> W2 --> W3 end subgraph Actual["As it runs"] direction TB A1["'auth'
every name comes first"] A2["inlineA
outer group's inline handler"] A3["inlineB
the route's inline handler"] A4["route contract validation
body / params / query schemas"] A5["controller action"] A1 --> A2 --> A3 --> A4 --> A5 end Written --> Actual ``` When relative order matters, register every piece as an alias. On a controller action, the last two steps cannot be reordered: a schema attached to the route is validated after all middleware, immediately before the action. ## Built-in Helpers | Helper | What it does | Mounted for you | |--------|--------------|-----------------| | `defineMiddleware` | Types a Hono middleware function for Guren | — | | `createSessionMiddleware` | Attaches a session to each request | With `createApp({ auth })` | | `createCsrfMiddleware` | Checks the CSRF token on state-changing requests | With `createApp({ auth })` | | `attachAuthContext` | Puts the auth context on each request | Always | | `requireAuthenticated` / `requireGuest` | Let only signed-in users / only guests through | No: add them to routes | | `createRateLimitMiddleware` | Limits requests per client | No: add it to routes | To opt out of the automatic session or CSRF middleware, pass `auth: { autoSession: false }` or `auth: { autoCsrf: false }`. ### `createSessionMiddleware` Attaches a session to the request context. The session id travels in a signed cookie, and the data is kept in memory (`MemorySessionStore`) unless you pass a store. Mount it yourself only in an app without the `auth` option: ```ts import { createSessionMiddleware } from '@guren/core' app.use('*', createSessionMiddleware()) ``` Read the session with `getSessionFromContext(ctx)` or `ctx.get('guren:session')`. `store` accepts a `SessionStore` or a function returning one. The function runs on every request, so a store that needs a runtime binding (Workers) or a connection (Redis) is not built at boot; memoize it yourself if building is expensive. To declare several stores and pick one per environment, use a `SessionManager` (see [Authentication](./sessions.md#selecting-a-store-with-sessionmanager)). ### Auth Guards `requireAuthenticated` and `requireGuest` read the auth context that the application attaches to every request, so you only add the guards: ```ts import { Router, requireAuthenticated, requireGuest } from '@guren/core' const router = new Router() .aliasMiddleware('auth', requireAuthenticated({ redirectTo: '/login' })) .aliasMiddleware('guest', requireGuest({ redirectTo: '/dashboard' })) router.middleware('auth').group((auth) => { auth.get('/settings', [SettingsController, 'index']) auth.get('/dashboard', [DashboardController, 'index']) }) ``` `redirectTo` applies to browsers. An agent tool call (see the [Agent interface](./agent-interface.md)) cannot follow a redirect, so both guards answer it with a JSON refusal instead: `401` from `requireAuthenticated`, `403` from `requireGuest`, or the `status` you pass. A `responseFactory` set beside `redirectTo` is skipped for those calls too. ### CSRF Protection The CSRF middleware checks the token on state-changing requests (POST, PUT, PATCH, DELETE). `createApp({ auth })` mounts it for every request, so add it by hand only in an app without the `auth` option: ```ts const router = new Router().aliasMiddleware('csrf', createCsrfMiddleware()) router.middleware('csrf').group((csrf) => { csrf.post('/posts', [PostsController, 'store']) }) ``` [CSRF Protection](./csrf.md) covers tokens in forms and requests. ### Rate Limiting Apply rate limiting to routes or groups: ```ts import { createRateLimitMiddleware } from '@guren/core' const router = new Router().aliasMiddleware('throttle', createRateLimitMiddleware({ limit: 60, windowMs: 60_000 })) router.middleware('throttle').group((throttle) => { throttle.post('/api/login', [AuthController, 'login']) }) ``` [Rate Limiting](./rate-limiting.md) covers keys, stores and response headers. ## Writing Custom Middleware Create middleware with `defineMiddleware`. The signed-in user is read through the auth context: ```ts import { AUTH_CONTEXT_KEY, defineMiddleware } from '@guren/core' import type { AuthContext } from '@guren/core' export const requireSubscription = defineMiddleware(async (ctx, next) => { const auth = ctx.get(AUTH_CONTEXT_KEY) as AuthContext | undefined const user = await auth?.user<{ isSubscribed: boolean }>() if (!user?.isSubscribed) { return ctx.json({ error: 'Subscription required' }, 403) } await next() }) ``` Save it under `app/Http/middleware/` and register it as an alias to use it by name: ```ts import { Router } from '@guren/core' import { requireSubscription } from '@/app/Http/middleware/subscription' const router = new Router().aliasMiddleware('subscribed', requireSubscription) router.middleware('subscribed').group((group) => { group.get('/premium', [PremiumController, 'index']) }) ``` --- # CSRF Protection Cross-Site Request Forgery (CSRF) protection prevents malicious websites from submitting forms on behalf of authenticated users. Guren's CSRF middleware issues a token per session (or a double-submit token for guests) and verifies it on POST, PUT, PATCH, and DELETE. The token spans two requests: it is issued on the GET that renders the form, and matched on the POST that submits it. ```mermaid sequenceDiagram participant B as Browser participant M as CSRF middleware participant C as Controller B->>M: GET /form (safe method, not verified) M->>M: issue the session token
(a double-submit token for guests) M->>C: run C-->>B: form with a hidden _token / XSRF-TOKEN cookie Note over B: A form on another site cannot read this token B->>M: POST /form (with _token or X-XSRF-TOKEN) M->>M: match the submitted token against the session value alt they match M->>C: run C-->>B: 200 else missing or mismatched M-->>B: 403 JSON (a 419 page for a browser navigation) end ``` ## Setup Enable CSRF protection by adding the middleware to your application: ```ts // src/app.ts import { createApp, createSessionMiddleware, createCsrfMiddleware } from '@guren/core' const app = createApp() // Optional — the token binds to a persisted session app.use('*', createSessionMiddleware()) app.use('*', createCsrfMiddleware()) ``` The middleware automatically: - Generates a token per session, or a stateless double-submit token for guests - Validates tokens on state-changing requests (POST, PUT, PATCH, DELETE) - Allows safe methods (GET, HEAD, OPTIONS, QUERY) without validation. QUERY (RFC 10008) is safe by contract, so keep QUERY handlers read-only, or add `'QUERY'` to the `methods` option to require tokens anyway ## Including the Token in Forms A native `
` must carry the token as a `_token` field, or Guren rejects it, and the browser shows a 419 "Page Expired" page. In an Inertia app, `useForm()` and `` send it for you (see [Inertia.js Integration](#inertiajs-integration)). Use the `csrfField()` helper to generate a hidden input field: ```ts // In your controller import { Controller, getCsrfToken, csrfField } from '@guren/core' import { pages } from '@/.guren/pages.gen' export default class FormController extends Controller { create() { const token = getCsrfToken(this.ctx) // Pass to your template/view return this.inertia(pages.forms.Create, { csrfToken: token }) } } ``` In your frontend form (React example): ```tsx function CreateForm({ csrfToken }: { csrfToken: string }) { return ( {/* form fields */}
) } ``` Or generate the hidden field directly: ```ts const hiddenField = csrfField(ctx) // Returns: ``` ## AJAX Requests For JavaScript/AJAX requests, include the token in a header: ```ts // The middleware sets a JavaScript-readable XSRF-TOKEN cookie const csrfToken = decodeURIComponent( document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]*)/)?.[1] ?? '', ) fetch('/api/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': csrfToken, }, body: JSON.stringify({ title: 'Hello' }), }) ``` Axios, and therefore Inertia.js, does this for you, so you only need the code above for plain `fetch`. The middleware accepts the token from three places, in this order: 1. The `X-CSRF-TOKEN` header 2. The `X-XSRF-TOKEN` header, read from the `XSRF-TOKEN` cookie 3. The `_token` field in an urlencoded, multipart, or JSON request body These names are not configurable. If you turn the cookie off (`cookie: false` below), pass the token to the page yourself with `getCsrfToken(ctx)` and send it as `X-CSRF-TOKEN`. Do this only for session-authenticated flows, because guest tokens verify against the cookie and cannot work without it. ## Configuration Options ```ts createCsrfMiddleware({ // Routes to exclude from CSRF validation exclude: ['/api/webhooks/*', '/api/public/*'], // Custom error handler onError: (ctx) => { return ctx.json({ error: 'Invalid CSRF token' }, 403) }, }) ``` Without `onError`, a rejected request gets one of two answers. A browser navigation (a request that accepts `text/html` and is not an Inertia visit, an XHR or a JSON caller) gets a 419 "Page Expired" page asking the user to go back, reload the page and submit the form again. Every other caller gets a 403 with the JSON body `{ "message": "CSRF token mismatch" }`. An `onError` you pass answers both. The remaining options rarely need changing: | Option | Default | Purpose | |--------|---------|---------| | `methods` | `['POST', 'PUT', 'PATCH', 'DELETE']` | Which HTTP methods require a token | | `cookie` | `true` | Issue the `XSRF-TOKEN` cookie on safe requests and successful mutations | | `cookieOptions` | `{ path: '/', sameSite: 'Lax' }` | Cookie attributes; `secure` is on when `NODE_ENV` is `production`, and in runtimes without `process` | ## Excluding Routes Some routes (like webhook endpoints) should skip CSRF validation: ```ts createCsrfMiddleware({ exclude: [ '/api/webhooks/stripe', '/api/webhooks/github', '/api/public/*', // Wildcard patterns supported ], }) ``` ## Manual Token Verification For custom validation logic, use `verifyCsrfToken()`: ```ts import { verifyCsrfToken, getCsrfToken } from '@guren/core' import { Router } from '@guren/core' export function registerWebRoutes(router: Router): void { router.post('/custom', async (ctx) => { const token = ctx.req.header('X-Custom-Token') if (!verifyCsrfToken(ctx, token)) { return ctx.json({ error: 'Invalid token' }, 403) } return ctx.json({ ok: true }) }) } ``` ## Token Regeneration A session-bound token follows the session id, so it changes when: - The session is first persisted (a brand-new session does not yet anchor a token) - `session.regenerate()` is called (recommended after login) Guest tokens carry no session id and are reused until a session exists. ```ts // After successful login const session = getSessionFromContext(ctx) await session.regenerate() // New CSRF token is generated automatically ``` ## Security Best Practices 1. **Always use HTTPS** - Tokens can be intercepted over HTTP 2. **Regenerate after login** - Prevents session fixation attacks 3. **Don't expose tokens in URLs** - Use POST bodies or headers 4. **Set secure cookie flags** - The session middleware handles the session cookie; the `XSRF-TOKEN` cookie follows `cookieOptions` ## Inertia.js Integration When using Inertia.js, CSRF is handled automatically through cookies. Ensure your Axios/fetch configuration includes credentials: ```ts // resources/js/app.tsx axios.defaults.withCredentials = true ``` Inertia automatically reads the `XSRF-TOKEN` cookie and includes it in requests. ### Submit through Inertia, not a native form That only covers requests Inertia sends through Axios. A native `
` submits as a full browser navigation, which carries no `X-XSRF-TOKEN` header — so Guren rejects it with the 419 "Page Expired" page unless the form itself carries a `_token` hidden field. In an Inertia page, prefer `useForm()`: ```tsx import { useForm } from '@inertiajs/react' function LogoutButton() { const { post, processing } = useForm() return ( ) } ``` `` works too, for a plain action link. Reach for a native form only when you deliberately want a full page submit. --- # Validation Validate request input against a schema and get typed, parsed values back. When the input is invalid, the request ends with a 422 response, or, on an Inertia request, a redirect back to the form with one error message per field. Write schemas with zod 4 (`import { z } from 'zod'`). [Schema Interface](#schema-interface) covers other libraries. ## Choosing Where to Validate | Where | Use it when | Read the values with | |-------|-------------|----------------------| | [Controller helpers](#controller-validation-helpers) | The default, inside a controller action | The return value of `this.validateBody()` and its siblings | | [Route contract](#route-contract-validation) | The route should also carry its types into codegen, OpenAPI and agent tools | `this.validated('route.name')` | | [Middleware](#middleware-validation) | The handler is an inline function, or the schema depends on the request | `getValidatedData(ctx)` | | [`validate()` / `validateSafe()`](#manual-validation) | The data does not come from a request: a job, a console command, a script | The return value | A `FormRequest` class layer also exists for code migrated from Laravel. It is deprecated; write new validation with one of the four above. ## Quick Start Call a helper at the top of the action. It returns the parsed value, so `data` below is typed `{ title: string; content: string }`: ```ts import { Controller, paginate } from '@guren/core' import { z } from 'zod' import { Post } from '@/app/Models/Post' import { PostResource } from '@/app/Http/Resources/PostResource' import { pages } from '@/.guren/pages.gen' const StorePostSchema = z.object({ title: z.string().min(1).max(200), content: z.string().min(10), }) const PageQuerySchema = z.object({ page: z.coerce.number().int().min(1).default(1), }) export default class PostsController extends Controller { async index() { const { page } = this.validateQuery(PageQuerySchema) const result = await Post.paginate({ page, perPage: 10 }) const paginator = paginate(result, { path: this.request.path ?? '/posts' }) return this.inertia(pages.posts.Index, { data: result.data.map((post) => new PostResource(post).toJSON()), pagination: { meta: paginator.meta(), links: paginator.links(), }, }) } async store() { const data = await this.validateBody(StorePostSchema) const post = await Post.create(data) return this.created({ post: new PostResource(post).toJSON() }) } } ``` If the body fails `StorePostSchema`, `validateBody()` throws a `ValidationException` and the action stops there. You do not catch it: the framework turns it into the response described in [Form Validation Errors](#form-validation-errors). ## Controller Validation Helpers Each helper reads one part of the request: | Helper | Input source | Async | On failure | |--------|--------------|-------|------------| | `this.validateBody(schema)` | JSON or form body | Yes | Throws `ValidationException` (422) | | `this.validateQuery(schema)` | Query string (`?page=1&sort=desc`) | No | Throws `ValidationException` (422) | | `this.validateParams(schema)` | Route parameters (`:id`, `:slug`) | No | Throws `ValidationException` (422) | | `this.validateBodySafe(schema)` | JSON or form body | Yes | Returns `{ success: false, errors }` | | `this.validateQuerySafe(schema)` | Query string | No | Returns `{ success: false, errors }` | | `this.validateParamsSafe(schema)` | Route parameters | No | Returns `{ success: false, errors }` | Use a `Safe` variant when the action decides what to do with the errors itself, as in [Displaying in Inertia](#displaying-in-inertia). On success it returns `{ success: true, data }`. Route parameters arrive as strings, so coerce them in the schema: ```ts const PostIdParamSchema = z.object({ id: z.coerce.number().int().positive(), }) export default class PostsController extends Controller { async show() { const { id } = this.validateParams(PostIdParamSchema) const post = await Post.findOrFail(id) return this.json(post) } } ``` ### Array-Style Query Parameters Repeated query keys reach your schema as arrays: `?tag=a&tag=b` becomes `{ tag: ['a', 'b'] }`. A key that appears only once stays a plain string, so use `union` when a parameter may appear one or more times: ```ts const FilterQuerySchema = z.object({ // ?tag=a&tag=b -> ['a', 'b'] / ?tag=a -> 'a' tag: z.union([z.string(), z.array(z.string())]).optional() .transform((value) => (typeof value === 'string' ? [value] : value ?? [])), }) ``` This applies to `this.validateQuery()` and to `query:` schemas attached via [route contracts](./route-contracts.md). ## Route Contract Validation A route that declares `params`, `query` or `body` schemas is validated before its handler runs, controller actions included. The action then reads the parsed values with `this.validated()` instead of naming the schema a second time: ```ts router.post('/posts', { name: 'posts.store', body: StorePostSchema }, [PostsController, 'store']) export default class PostsController extends Controller { async store() { const { body } = this.validated('posts.store') const post = await Post.create(body) return this.created({ post }) } } ``` On a controller action, a failure throws the same `ValidationException` (422) as the helpers, so Inertia forms display it unchanged. A route whose handler is an inline function answers the 422 itself, in the middleware's shape (see [Form Validation Errors](#form-validation-errors)). See [Reading Validated Input](./route-contracts.md#reading-validated-input). ## Middleware Validation ### `validateRequest(schema)` `validateRequest()` builds a middleware that validates the request body before the handler runs. The handler reads the parsed body with `getValidatedData()`: ```ts import { Router, getValidatedData, validateRequest } from '@guren/core' import { z } from 'zod' const CreatePostSchema = z.object({ title: z.string().min(1), content: z.string().min(1), }) const router = new Router() router.post('/posts', async (ctx) => { const data = getValidatedData>(ctx)! return ctx.json({ post: await Post.create(data) }) }, validateRequest(CreatePostSchema)) ``` `getValidatedData()` returns `undefined` when the middleware has not run on the route, hence the `!`. On failure the middleware answers by itself, with a 422 holding the first message for each top-level field: ```json { "errors": { "title": "Too small: expected string to have >=1 characters" } } ``` ### `validateRequestWith(schemaFactory)` Use it when the schema depends on the request. The factory runs synchronously, so it cannot await the signed-in user; resolve what it needs in a middleware mounted before it, as `resolveIsAdmin` does here: ```ts import { AUTH_CONTEXT_KEY, Router, defineMiddleware, validateRequestWith } from '@guren/core' import type { AuthContext } from '@guren/core' const resolveIsAdmin = defineMiddleware(async (ctx, next) => { const auth = ctx.get(AUTH_CONTEXT_KEY) as AuthContext | undefined const user = await auth?.user<{ role: string }>() ctx.set('isAdmin', user?.role === 'admin') await next() }) const router = new Router() router.put('/users/:id', [UserController, 'update'], resolveIsAdmin, validateRequestWith((ctx) => { const isAdmin = ctx.get('isAdmin') === true return z.object({ name: z.string().min(1), email: z.email(), // Only admins can change roles role: isAdmin ? z.enum(['user', 'admin']) : z.never().optional(), }) })) ``` The action reads the parsed body with `getValidatedData(this.ctx)`. ### Custom Error Handling Both middleware take an `onError` option that replaces the 422 response. It receives the same field-to-message map: ```ts validateRequest(schema, { onError: (ctx, errors) => { return ctx.json({ message: 'Validation failed', errors: Object.entries(errors).map(([field, message]) => ({ field, message })), }, 422) }, }) ``` `status` changes the failure status instead, and `fallbackMessage` sets the message used when no error names a field. ## Manual Validation For data that does not come from a request, call `validate()` or `validateSafe()`: ```ts import { validate, validateSafe } from '@guren/core' // Returns the parsed data, or throws the schema's own error (a ZodError for zod) const data = validate(schema, input) // Never throws const result = validateSafe(schema, input) if (result.success) { console.log(result.data) } else { console.log(result.errors) // { field: 'first message' } } ``` ## Form Validation Errors Each path reports errors in its own shape. "Nested key" is how a failure on `address.postalCode` is keyed: | Source | Shape | Messages per key | Nested key | |--------|-------|------------------|------------| | Helpers and contract `body`, JSON request | `{ message, errors: { [key]: string[] } }`, 422 | All | `address.postalCode` | | Contract `params` / `query`, JSON request | `{ message, errors: { [key]: string[] } }`, 422 | One | `address` | | Any `ValidationException`, Inertia request | The page's `errors` prop: `{ [key]: string }` | One | As thrown | | `this.validateBodySafe()` and siblings | `{ success: false, errors: { [key]: string } }` | One | `address.postalCode` | | `validateRequest()`, `validateSafe()`, inline-handler contracts | `{ errors: { [key]: string } }` | One | `address` | A key of `address` is used whenever the key is the top-level field; an error that names no field there is keyed `message`. ### JSON Requests A JSON or API request that throws `ValidationException` gets a 422: ```json { "message": "The given data was invalid.", "errors": { "email": ["Invalid email address"], "password": ["Too small: expected string to have >=8 characters"] } } ``` ### Automatic Handling on Inertia Requests An Inertia request (one carrying the `X-Inertia` header) gets no JSON. Instead: 1. The errors are stored for the next request only. 2. The response is a `303` redirect back to the previous page. 3. On that page load, the errors arrive in the shared `errors` prop, one message per field. ```tsx function Login({ errors }: { errors?: Record }) { return ( {errors?.email && {errors.email}} ) } ``` This covers failures from `validateBody`, `validateQuery`, `validateParams` and route contracts, and any `ValidationException.withMessages(...)` you throw yourself. A few details: - The errors are stored in the session when the app has one (`createApp({ auth })` mounts it), and otherwise in a short-lived cookie, so a fresh scaffold shows them too. - The redirect goes to the path of the `Referer` header when it names the request's host or the host of `APP_URL`, and to `/` when there is no `Referer` or it names another host. Only the path and query are kept, so a forged `Referer` cannot send the browser off the site. Behind a proxy that does not forward the `Host` header, the request names the proxy's upstream address, so set `APP_URL` to the public URL; `X-Forwarded-Host` is not read. - To replace this behavior, register your own renderer from a service provider's `boot()`: `this.container.make('exception.handler').render(ValidationException, (error, ctx) => …)`. It runs before the built-in one. ### Displaying in Inertia To render the errors on the same response instead of redirecting, use a `Safe` helper and pass its `errors` to the page. Declare the page's `errors` prop with `ValidationErrors`; codegen reads the page's `Props`, so `this.inertia()` checks the controller against it: ```ts import { pages } from '@/.guren/pages.gen' async store() { const result = await this.validateBodySafe(schema) if (!result.success) { return this.inertia(pages.users.Create, { errors: result.errors, }) } await User.create(result.data) return this.redirect('/users') } ``` ```tsx import type { ValidationErrors } from '@guren/core' interface Props { errors?: ValidationErrors<'email' | 'password'> } export default function CreateUser({ errors }: Props) { return (
{errors?.email && {errors.email}} {errors?.password && {errors.password}}
) } ``` ## Common Patterns ### Nested Objects ```ts const addressSchema = z.object({ street: z.string(), city: z.string(), postalCode: z.string().regex(/^\d{5}$/), }) const userSchema = z.object({ name: z.string(), address: addressSchema, }) ``` ### Arrays ```ts const schema = z.object({ tags: z.array(z.string()).min(1).max(10), items: z.array(z.object({ productId: z.number(), quantity: z.number().positive(), })), }) ``` ### Optional with Defaults ```ts const schema = z.object({ page: z.coerce.number().positive().default(1), perPage: z.coerce.number().positive().max(100).default(20), sortBy: z.enum(['created', 'updated', 'name']).default('created'), }) ``` ### Transformations ```ts const schema = z.object({ email: z.email().toLowerCase(), tags: z.string().transform(s => s.split(',').map(t => t.trim())), date: z.string().transform(s => new Date(s)), }) ``` ### Refinements ```ts const schema = z.object({ password: z.string().min(8), confirmPassword: z.string(), }).refine(data => data.password === data.confirmPassword, { message: 'Passwords must match', path: ['confirmPassword'], }) ``` ## Schema Interface Validation calls the schema's own methods rather than importing Zod, so any object with this shape works. `validate()` needs only `parse()`; everything else needs only `safeParse()`: ```ts interface ValidationSchema { parse(data: unknown): T safeParse(data: unknown): | { success: true; data: T } | { success: false; error: { issues: Array<{ path: PropertyKey[]; message: string }> } } } ``` The error keys come from `issues[].path`, so a schema from another library needs a small adapter that returns this shape. The tools that read schemas structurally (`guren codegen`, which writes the typed route manifests; OpenAPI generation; `guren context`) understand zod 4 only. They skip a schema written with the zod v3 API (the `zod@3` package or the `zod/v3` subpath) and print a warning. ## Compiled Parsing (zod 4.5+) zod 4.5 can compile schemas into a generated fast path. Apps scaffolded with `create-guren-app` enable it out of the box: the first import in `src/app.ts` is ```ts import 'zod/compile' ``` Every schema built after that import parses through the compiled path. Guren's validation helpers, route contracts (`params`, `query`, `body`, `output`) and validation middleware all call your schema's own `parse`/`safeParse`, so they speed up with no further changes. To adopt it in an existing app, move your `zod` dependency to `^4.5.0` and add the import as the **first** line of your entry module, before any module that defines schemas. In our benchmarks on Bun, validating a 100-item list output dropped from about 19µs to 1.2µs, and a five-field body parsed about four times faster. End to end, an API endpoint returning a validated 100-item list served roughly 10% more requests per second at a lower median latency. Your numbers will scale with how much of a route's time is spent validating. Three things to know: - **Import order matters.** Schemas built before the import keep the regular parser. Keep the import first in the entry module. - **Restricted runtimes are handled.** If your runtime forbids generated code (a strict CSP), call `z.config({ jitless: true })`; compilation is skipped and everything still works. Schema features the compiler does not support also fall back to the regular parser, so compilation never throws. - **Keep refinements side-effect free.** On invalid input, `.refine()` and `.transform()` callbacks can run twice: the fast path runs first, then the fallback that builds the full error. Validation results are unchanged, but side effects inside those callbacks would happen twice. Schemas from other libraries are unaffected; they keep their own `parse`/`safeParse`. --- # Error Handling An exception thrown anywhere in a request ends up at the `ExceptionHandler`, which decides what gets reported and what the client sees. You customize it from a service provider, and an ordinary `try`/`catch` inside a controller handles the errors you want to recover from on the spot. The handler answers differently in development and in production. ## ExceptionHandler The `ExceptionHandler` decides what is reported and what the client sees for every exception a request throws. The app creates one at boot and installs it as Hono's `onError` handler. Customize it from a service provider's `boot()`, where the container hands you that instance: ```ts // app/Providers/ExceptionServiceProvider.ts import { ServiceProvider } from '@guren/core' import type { ExceptionHandler } from '@guren/core' class PaymentDeclinedError extends Error { constructor(readonly reason: string) { super('Payment declined') } } export class ExceptionServiceProvider extends ServiceProvider { register(): void {} boot(): void { const handler = this.container.make('exception.handler') // Expected failures that should not reach your error tracker handler.dontReport(PaymentDeclinedError) // Runs for every other exception handler.report((error) => { console.error('[report]', error) }) // A response for one exception class; everything else keeps the default rendering handler.render(PaymentDeclinedError, (error, ctx) => ctx.json({ message: error.message, reason: error.reason }, 402), ) } } ``` Register the provider in `createApp({ providers: [ExceptionServiceProvider] })`. | Method | What it does | |---|---| | `report(callback)` | Adds a reporter. Every reporter runs for each exception not excluded by `dontReport()`; one that throws is logged and the others still run | | `dontReport(ErrorClass)` | Skips the reporters for that class | | `render(ErrorClass, renderer)` | Answers that class with your own response. Renderers are tried in registration order, and the first match wins | A class matches by `instanceof` or by its name, so an exception from another copy of a package still matches. With no reporter registered, the handler logs 5xx exceptions to the console so a production failure is never silent. ## Replacing Hono's `onError` The exception handler owns Hono's `onError` hook: it is installed while the app boots, after the `boot(hono)` callback runs. A handler you set with `app.hono.onError()` before `app.boot()` is therefore replaced, so customize the exception handler above instead. To take the hook over completely, register a subclass of `ErrorServiceProvider`. The app then uses it in place of the built-in one: ```ts // app/Providers/AppErrorServiceProvider.ts import { ErrorServiceProvider } from '@guren/core' import type { Hono } from 'hono' export class AppErrorServiceProvider extends ErrorServiceProvider { boot(): void { const hono = this.container.make('hono') hono.onError((error, ctx) => { const isDev = process.env.NODE_ENV !== 'production' return ctx.json({ error: isDev ? error.message : 'Internal Server Error' }, 500) }) } } ``` This skips everything the exception handler does, including the status of `HttpException` and `ModelNotFoundException`, so prefer `render()` unless you need that. ## Built-in Exception Classes Guren provides typed exception classes for common HTTP error scenarios: ```ts import { HttpException, NotFoundHttpException, AuthenticationException, AuthorizationException, ValidationException, MethodNotAllowedException, ModelNotFoundException, } from '@guren/core' // 404 Not Found throw new NotFoundHttpException('Post not found') // 404 Not Found (thrown automatically by Model.findOrFail()) throw new ModelNotFoundException('Post', 42) // 401 Unauthorized (thrown automatically by auth.userOrFail()) throw new AuthenticationException('Authentication required') // 403 Forbidden throw new AuthorizationException('You do not have permission to edit this post') // 422 Unprocessable Entity (thrown automatically by validateBody/Query/Params) throw new ValidationException({ title: ['Title is required'] }) // 405 Method Not Allowed throw new MethodNotAllowedException('GET method is not allowed for this endpoint') // Generic HTTP exception with custom status throw new HttpException(429, 'Rate limit exceeded') ``` ### Duck-typed `statusCode` The `ExceptionHandler` supports any error with a numeric `statusCode` property, not just `HttpException` subclasses. This means `ModelNotFoundException` (exported from `@guren/core`, with `statusCode: 404`) is automatically rendered as a 404 response without any extra configuration. For errors with `statusCode >= 500`, the message is hidden in production (replaced with "Internal Server Error"). Outside debug, a 404 message the framework composed from the record reads `Not Found` instead: the one `findOrFail()` and route model binding throw (`Post not found for id=42`), the ones `NotFoundHttpException.forModel()` and the other `for*()` constructors write, and a 404 thrown with no message. `denyAsNotFound()` and `abort(404)` default to that same `Not Found`, so with the framework's defaults a record a policy hides reads exactly like one that does not exist, and the response cannot tell a stranger which ids exist. A message you write yourself, as in `abort(404, 'That invitation has expired')`, `denyAsNotFound('…')` or `new NotFoundHttpException('…', 'Invitation', id)`, is shown as written, so keep record details out of it. Only the framework's own construction counts: a `resourceType` or `modelName` field on your exception does not make its message replaceable. Only the body's top-level `message` changes, and only while it is the exception's own: a body your exception's `toResponse()` builds keeps its shape, and a message that `toResponse()` writes itself is kept. The exception is never modified, so reporters and logs see the original message. ## HTTP Exceptions Throw `HTTPException` to return specific HTTP status codes: ```ts import { HTTPException } from 'hono/http-exception' import { Router } from '@guren/core' const router = new Router() router.get('/posts/:id', async (ctx) => { const post = await Post.find(ctx.req.param('id')) if (!post) { throw new HTTPException(404, { message: 'Post not found' }) } return ctx.json({ post }) }) ``` Common HTTP exceptions: ```ts // 400 Bad Request throw new HTTPException(400, { message: 'Invalid request data' }) // 401 Unauthorized throw new HTTPException(401, { message: 'Authentication required' }) // 403 Forbidden throw new HTTPException(403, { message: 'Access denied' }) // 404 Not Found throw new HTTPException(404, { message: 'Resource not found' }) // 422 Unprocessable Entity throw new HTTPException(422, { message: 'Validation failed' }) // 429 Too Many Requests throw new HTTPException(429, { message: 'Rate limit exceeded' }) // 500 Internal Server Error throw new HTTPException(500, { message: 'Server error' }) ``` ## Not Found Handler Customize 404 responses: ```ts app.hono.notFound((ctx) => { // Return JSON for API requests if (ctx.req.header('Accept')?.includes('application/json')) { return ctx.json({ error: 'Not found' }, 404) } // Return HTML for browser requests return ctx.html('

Page Not Found

', 404) }) ``` ## Debug Details While `NODE_ENV` is not `production`, the exception handler shows what went wrong: - A browser request that ends in a 5xx gets the debug page: the exception's name and message, the stack trace, the request's method, URL and headers, and the `NODE_ENV`, Bun version and platform. A browser request is one that accepts `text/html` and is not an Inertia visit or an XHR. - An Inertia visit, an XHR or a JSON caller gets the JSON body with the exception's name and stack added. - A browser request that ends in a 4xx gets the plain error page with its message. A 4xx is the caller's mistake, and a stack trace would not help with it. In production the details are dropped, the message of a 5xx that is not an `HttpException` becomes `Internal Server Error`, and a browser gets the generic error page. A 404 message the framework composed from a record reads `Not Found`, so with the defaults a missing record and one a policy hides cannot be told apart. Any other `HttpException` keeps its own message in production, a 404 you wrote a message for included, so do not put internal details in one. To turn details on and off by another rule, bind your own handler under `exception.handler` in a provider's `register()`. The framework adds its own renderers in `boot()`, so they attach to yours: ```ts // app/Providers/ExceptionServiceProvider.ts import { ServiceProvider, createExceptionHandler } from '@guren/core' export class ExceptionServiceProvider extends ServiceProvider { register(): void { this.container.instance('exception.handler', createExceptionHandler({ // Details only when NODE_ENV is exactly 'development' isDebug: () => process.env.NODE_ENV === 'development', })) } // boot() as in the ExceptionHandler section above } ``` `createApp()` has no `debug` option; this binding is where the choice is made. The debug page lists every request header, but shows `[redacted]` in place of the values of `Cookie`, `Authorization`, `Proxy-Authorization`, `X-XSRF-TOKEN` and `X-CSRF-Token`. The stack trace, file paths and the other headers are printed as they are, so keep details off on any server other people can reach. `debugErrorMiddleware()` is deprecated and will be removed in 3.0.0. Its `catch` never sees an error (see [Error Middleware](#error-middleware)), and the exception handler now renders the same page, so remove it from your middleware. `bunx guren upgrade --check-only` lists the files that import it. ## Controller Error Handling With `validateBody`/`validateQuery`/`validateParams`, `findOrFail`, and `userOrFail`, most error handling is automatic — no try-catch needed: ```ts import { Controller } from '@guren/core' import { z } from 'zod' import { PostResource } from '@/app/Http/Resources/PostResource' import { pages } from '@/.guren/pages.gen' import type { UserRecord } from '@/app/Models/User' const StorePostSchema = z.object({ title: z.string().min(1), content: z.string().min(10) }) const PostIdSchema = z.object({ id: z.coerce.number().int().positive() }) export default class PostController extends Controller { async store(): Promise { const data = await this.validateBody(StorePostSchema) // 422 on failure const user = await this.auth.userOrFail() // 401 if not logged in const post = await Post.create(data, { set: { authorId: user.id } }) return this.redirect(`/posts/${post.id}`) } async show(): Promise { const { id } = this.validateParams(PostIdSchema) // 422 on invalid params const post = await Post.findOrFail(id) // 404 if missing return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } } ``` The `ExceptionHandler` catches and renders all thrown exceptions automatically. Use try-catch only when you need custom error recovery logic within a specific controller method. ## Validation Errors Use `formatValidationErrors` to convert Zod errors to a flat object: ```ts import { formatValidationErrors } from '@guren/core' import { z } from 'zod' const schema = z.object({ email: z.email(), password: z.string().min(8), }) const result = schema.safeParse(data) if (!result.success) { const errors = formatValidationErrors(result.error) // { email: 'Invalid email', password: 'String must contain at least 8 character(s)' } } ``` With a fallback message: ```ts const errors = formatValidationErrors(result.error, 'Please check your input') ``` ## Error Middleware A middleware cannot catch an `Error` that a later handler throws. Hono hands it to `onError`, which is the exception handler, at the point it is thrown, so a `try { await next() } catch` around `next()` never sees it. Put shared error logic in a reporter or a renderer (see [ExceptionHandler](#exceptionhandler)), and keep `try`/`catch` for code you call directly, as in [Controller Error Handling](#controller-error-handling). ## Inertia Error Pages With Inertia, a page visit that hits a missing record should land on an error page component rather than a JSON body. Register a renderer for the two not-found exceptions in a provider, and answer non-browser callers with JSON: ```ts // app/Providers/ErrorPageServiceProvider.ts import { ModelNotFoundException, NotFoundHttpException, ServiceProvider, inertia } from '@guren/core' import type { ExceptionHandler } from '@guren/core' export class ErrorPageServiceProvider extends ServiceProvider { register(): void {} boot(): void { const handler = this.container.make('exception.handler') for (const errorClass of [NotFoundHttpException, ModelNotFoundException]) { handler.render(errorClass, (error, ctx) => { const message = handler.shouldShowDetails() ? error.message : 'Not Found' const wantsPage = ctx.req.header('X-Inertia') === 'true' || (ctx.req.header('accept') ?? '').includes('text/html') if (!wantsPage) return ctx.json({ message }, 404) return inertia('Error', { status: 404, message }, { status: 404, request: ctx.req.raw, container: this.container, }) }) } } } ``` The renderer passes `error.message` on only while debug details are on. `findOrFail()`'s message names the model and the id, and a policy that hides a record with `denyAsNotFound()` raises a `NotFoundHttpException` too, so a body built from the message would tell a hidden record from a missing one. Keep these renderers to specific classes. `ValidationException`, `AuthenticationException` and `AuthorizationException` all extend `HttpException`, so a renderer for `HttpException` would also replace how validation, authentication and authorization failures are answered, the validation redirect included. React error component: ```tsx // resources/pages/Error.tsx export default function Error({ status, message }: { status: number; message: string }) { const titles: Record = { 404: 'Page Not Found', 403: 'Forbidden', 500: 'Server Error', 503: 'Service Unavailable', } return (

{status}

{titles[status] ?? 'Error'}

{message}

Go Home
) } ``` ## Database Errors Use `Model.findOrFail()` instead of manual null-checking. It throws `ModelNotFoundException` (404) automatically: ```ts // Before — manual null check async show(): Promise { const post = await Post.find(Number(this.request.param('id'))) if (!post) { throw new HTTPException(404, { message: 'Post not found' }) } return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } // After — automatic 404 async show(): Promise { const { id } = this.validateParams(PostIdSchema) const post = await Post.findOrFail(id) // throws ModelNotFoundException (404) return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() }) } ``` ## Async Error Boundaries Wrap async operations with error boundaries: ```ts async function withErrorBoundary( operation: () => Promise, fallback: T, onError?: (error: unknown) => void ): Promise { try { return await operation() } catch (error) { onError?.(error) return fallback } } // Usage const posts = await withErrorBoundary( () => Post.all(), [], (error) => console.error('Failed to fetch posts:', error) ) ``` ## Development vs Production The exception handler already answers differently by environment, so most apps need no code here: | | Development (`debug` on) | Production | |---|---|---| | Message of a 5xx | The exception's own | `Internal Server Error`, except an `HttpException`, which keeps its own | | Message of a 404 | The exception's own (`Post not found for id=42`) | `Not Found` when the framework composed it from the record; a message you wrote is kept | | Exception name and stack | Included in the JSON body | Omitted | | A browser's 5xx | The debug page | A generic error page | `debug` follows `NODE_ENV`; [Debug Details](#debug-details) shows how to decide it another way. To change what one class of error answers, register a renderer (see [ExceptionHandler](#exceptionhandler)). ## Best Practices 1. **Use the ExceptionHandler** - Centralize error handling logic instead of scattering try-catch blocks. 2. **Always catch async errors** - Unhandled promise rejections can crash your server. 3. **Log errors with context** - Include request ID, user ID, and relevant data. 4. **Use appropriate status codes** - 4xx for client errors, 5xx for server errors. 5. **Don't expose sensitive data** - Hide stack traces and internal details in production. 6. **Provide user-friendly messages** - Technical errors should be translated to helpful messages. 7. **Monitor errors** - Use error tracking services in production. 8. **Use built-in exceptions** - Prefer `NotFoundHttpException`, `AuthorizationException`, etc. over generic `HTTPException`. --- # Database Guren reads and writes the database through models built on Drizzle tables, with a query API shaped like Laravel's Eloquent and typed from your schema. A new app uses SQLite and needs no setup; PostgreSQL, MySQL and Aurora Serverless are a configuration change away. This page sets the database up: the connection, the schema and its migrations, and seed data. ## Connecting to the Database The scaffold writes `config/database.ts` for the driver you picked with `create-guren-app --db`, and `createApp({ config })` lists it, so the ORM connects at boot with the app's validated environment. Every driver exposes the same functions (`getDatabase`, `migrateDatabase`, `closeDatabase`, `configureOrm`, `seedDatabase`, `resetDatabase`, `migrationStatus`) and an `AppSeederContext` type, so models and queries do not change when you switch. | Driver | `--db` | Factory in `config/database.ts` | |--------|--------|---------------------------------| | SQLite (the default) | `sqlite` | `createSqliteDatabase` | | PostgreSQL | `postgres` | `createPostgresDatabase` | | MySQL | `mysql` | `createMySqlDatabase` | | Aurora Serverless (AWS Data API) | none: write it by hand | `createAwsDataApiDatabase` | | Cloudflare D1 | none: see the [Cloudflare guide](./cloudflare.md#database-d1) | D1's own factory | Each factory reads its connection settings from `config/env.ts` through a resolver; [Configuration](./configuration.md#the-database-connection) explains the resolver's `context` argument. ### SQLite New projects use SQLite through Bun's built-in driver, with no Docker or external database: ```ts // config/database.ts import { createSqliteDatabase, defineDatabaseConfig, type SqliteSeederContext } from '@guren/core' import env from './env.js' const database = createSqliteDatabase({ migrationsFolder: new URL('../db/migrations', import.meta.url), seedersFolder: new URL('../db/seeders', import.meta.url), filename: (context) => { const values = context?.env ?? env.parse(undefined, { mode: 'report' }).values // `bun test` sets NODE_ENV=test, so the suite uses its own file. return process.env.NODE_ENV === 'test' ? values.TEST_DATABASE_URL ?? './data/guren.test.db' : values.DATABASE_URL ?? './data/guren.db' }, }) export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database export type AppSeederContext = SqliteSeederContext export default defineDatabaseConfig(database, { seedOnBoot: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test', }) ``` With `seedOnBoot` true, the app runs the seeders at boot once the migrations folder holds migrations. Scaffolds turn it on only under `NODE_ENV=development` (which `bun run dev` sets) and `NODE_ENV=test` (which `bun test` sets). Any other value, an unset `NODE_ENV` included, skips it, so a server started without `NODE_ENV` never creates the seeders' demo accounts; run `bunx guren db:seed` explicitly there. Tests use a separate file; see [Testing](./testing.md#test-database-isolation). Apps scaffolded earlier pass `seedOnBoot: process.env.NODE_ENV !== 'production'`, which also seeds when `NODE_ENV` is unset. `bunx guren doctor` warns about it and says what to edit; nothing rewrites the file for you. Replace the comparison with `(process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test')`, keeping the rest of the expression, and run `bin/serve.ts` under `NODE_ENV=development` in the script `bun run dev` starts it with (`"dev:server": "NODE_ENV=development bun --hot bin/serve.ts"`), or `bun run dev` stops seeding. > [!TIP] > Use SQLite for development and testing, then switch to PostgreSQL for production. Your models and queries work unchanged. ### PostgreSQL `DATABASE_URL` is declared in the scaffolded `config/env.ts`: ```ts // config/database.ts import { createPostgresDatabase, defineDatabaseConfig, type PostgresSeederContext } from '@guren/core' import env from './env.js' const database = createPostgresDatabase({ migrationsFolder: new URL('../db/migrations', import.meta.url), seedersFolder: new URL('../db/seeders', import.meta.url), connectionString: (context) => (context?.env ?? env.parse(undefined, { mode: 'report' }).values).DATABASE_URL ?? 'postgres://guren:guren@localhost:54322/guren', }) export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database export type AppSeederContext = PostgresSeederContext export default defineDatabaseConfig(database, { seedOnBoot: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test', }) ``` Tables are declared with `pgTable`: ```ts // db/schema.ts import { pgTable, serial, text, timestamp } from '@guren/orm/drizzle/pg' export const posts = pgTable('posts', { id: serial('id').primaryKey(), title: text('title').notNull(), body: text('body').notNull(), status: text('status').notNull().default('draft'), publishedAt: timestamp('published_at', { withTimezone: true }), createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow(), }) ``` On PostgreSQL, give every timestamp column `{ withTimezone: true }`. A `timestamp without time zone` stores a bare wall clock with no offset, so `defaultNow()` records it in the database session's zone while your app reads it back as UTC, and any client other than your app sees a different instant. Scaffolds already emit it, and `bunx guren check` warns about a column declared without it. That warning reads the schema statically, so a clean result means nothing was found, not that every column is right. ### MySQL Use `createMySqlDatabase` when your app runs on MySQL-compatible databases. ```ts // config/database.ts import { createMySqlDatabase, defineDatabaseConfig, type MySqlSeederContext } from '@guren/core' import env from './env.js' const database = createMySqlDatabase({ migrationsFolder: new URL('../db/migrations', import.meta.url), seedersFolder: new URL('../db/seeders', import.meta.url), connectionString: (context) => (context?.env ?? env.parse(undefined, { mode: 'report' }).values).DATABASE_URL ?? 'mysql://guren:guren@localhost:33306/guren', }) export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database export type AppSeederContext = MySqlSeederContext export default defineDatabaseConfig(database, { seedOnBoot: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test', }) ``` ### Aurora Serverless (AWS Data API) Use `createAwsDataApiDatabase` when your app runs on AWS Lambda against Aurora Serverless v2 with the RDS Data API enabled. The Data API is HTTP-based, so there is no connection pool to manage and the Lambda function does not need to run inside a VPC. ```ts // config/database.ts import { createAwsDataApiDatabase, defineDatabaseConfig, type ConnectionContext } from '@guren/core' import env from './env.js' const values = (context?: ConnectionContext) => context?.env ?? env.parse(undefined, { mode: 'report' }).values const database = createAwsDataApiDatabase({ migrationsFolder: new URL('../db/migrations', import.meta.url), seedersFolder: new URL('../db/seeders', import.meta.url), // A resolver returning undefined falls back to the environment variable: // DATABASE_NAME, DATABASE_RESOURCE_ARN, DATABASE_SECRET_ARN database: (context) => values(context).DATABASE_NAME, resourceArn: (context) => values(context).DATABASE_RESOURCE_ARN, secretArn: (context) => values(context).DATABASE_SECRET_ARN, }) export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase } = database export default defineDatabaseConfig(database, { seedOnBoot: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test', }) ``` Declare the three keys in `config/env.ts` (see [Configuration](./configuration.md#declaring-the-environment)), for example as `Env.string().optional()`. Install the driver package alongside it: ```bash bun add @aws-sdk/client-rds-data ``` The adapter exposes the same runtime API as the other drivers, and migrations use the standard drizzle-kit folders. One deliberate difference: `getDatabase()` does **not** run pending migrations automatically. On Lambda that check would cost several serialized Data API round trips on every cold start. Run migrations out of band (`bun run db:migrate`, or the console handler once deployed), or opt back in with `migrateOnStart: true`. For `drizzle-kit generate`/`push` against the Data API, set `driver: 'aws-data-api'` in `drizzle.config.ts` with the same `database`/`resourceArn`/`secretArn` credentials. > [!NOTE] > Authentication uses the standard AWS SDK credential chain (IAM role on Lambda, `AWS_PROFILE` locally). Pass `clientOptions` to override the region or credentials explicitly. ## Schema and Migrations Tables are declared in `db/schema.ts` with Drizzle's builders for your driver. A fresh SQLite app starts with a `users` table: ```ts // db/schema.ts import { sqliteTable, integer, text } from '@guren/orm/drizzle/sqlite' export const users = sqliteTable('users', { id: integer('id').primaryKey({ autoIncrement: true }), name: text('name').notNull(), email: text('email').notNull(), createdAt: text('created_at').notNull().$defaultFn(() => new Date().toISOString()), }) ``` After changing the schema, generate a migration from it and apply it: ```bash bunx guren make:migration --name add_posts_table bun run db:migrate ``` ### Generating migrations The command reads the first of `drizzle.config.ts`, `.mts`, `.js`, `.mjs` and `.json` that exists, in that order, for the schema path, output directory, and dialect. You can override the paths: ```bash bunx guren make:migration --schema ./custom/schema.ts --out ./custom/migrations ``` Overrides cannot be combined with drizzle-kit's `--config`, so Guren reads the config itself and restates its `dialect` (and `driver`) on the command line. Fields you did not override keep their configured values, so `--schema` alone still writes to the config's `out`. If a config field cannot be restated as a flag, the command names it rather than letting the migration differ silently. A config whose `schema` is a list is one such case: drizzle-kit would keep only the last entry, so an override without `--schema` stops with an error. An app with no drizzle config has nothing to declare the dialect, so state it directly: ```bash bunx guren make:migration --dialect postgresql ``` The command runs the drizzle-kit your app installs, found in its `node_modules` or a parent's (a hoisted workspace install). With none installed it stops and asks for `bun install`; it never fetches a copy from npm, whose version may take other flags. > [!NOTE] > Once a migration has shipped to any environment, treat it as immutable. Create a follow-up migration to correct mistakes. ### When migrations run `db:migrate` is not the only thing that applies them. Every driver except the Data API and D1 adapters applies pending migrations on the first `getDatabase()` or `configureOrm()` call, in every environment: `bun run dev`, `bun test`, and the container the scaffolded `Dockerfile` starts with `bun bin/serve.ts` all migrate at boot, which is what lets a deploy that ships only a new image arrive migrated. A boot that applies something prints one line naming what it applied and where it came from; an up-to-date database boots silently. The cost of that convenience is that a migration you did not mean to keep still reaches the database. A generator writes one as a new, untracked folder under `db/migrations/`, and neither `git switch` nor `git branch -D` removes an untracked file, so a migration generated on a branch you threw away is still on disk and still pending. Remove it with `git clean -fd` (`git clean -fdn` first shows what that would take) rather than expecting the branch to take it with it. Removing the folder only helps before a boot has applied it, and a dev server that reloads while the generator is still editing files can get there first. After that, the tracker keeps a row for a migration no folder carries, the migrator skips it, and whatever it created stays in the database. `db:status` lists such a row as orphaned, and every boot warns about it before migrating. The two exceptions never migrate at boot, for different reasons. The Data API adapter is opt-in (`migrateOnStart`) because the check costs serialized round trips on every Lambda cold start. D1 has no runtime path at all: migrations go through `wrangler d1 migrations apply `, and `migrateDatabase()` says so rather than trying. ### Destructive migrations drizzle-kit writes whatever the schema diff implies. When a column is removed and another added in one edit, it asks whether that is a rename, and only in an interactive terminal; run by an agent or a script, it writes a `DROP COLUMN`, and the next boot applies it. Guren reads every pending migration before it applies anything and reports these statements: | Kind | What it matches | |---|---| | `drop-table`, `drop-column`, `drop-schema` | `DROP TABLE`, `ALTER TABLE … DROP COLUMN`, `DROP SCHEMA` / `DROP DATABASE` | | `alter-column-type` | PostgreSQL `ALTER COLUMN … SET DATA TYPE`, MySQL `MODIFY COLUMN` / `CHANGE COLUMN` | | `table-rebuild` | SQLite's `__new_` copy, drop and rename, which drizzle-kit writes for most column changes. A rebuild whose `CREATE TABLE __new_
` copies every column with the same or a wider type (an added default or foreign key) passes, unless another table references it with `ON DELETE CASCADE`, `SET NULL` or `SET DEFAULT` and foreign keys stay on while it runs (Cloudflare D1), where its `DROP TABLE` deletes or rewrites those rows | | `rename` | `RENAME TO`, `RENAME COLUMN`, `RENAME TABLE` | | `truncate`, `delete-all` | `TRUNCATE` (a MySQL `TRUNCATE PARTITION` too), and `DELETE FROM` with no `WHERE` | | `drop-partition` | MySQL `ALTER TABLE … DROP PARTITION`, which drops the partition's rows | | `drop-cascade` | `DROP TYPE … CASCADE`, `DROP DOMAIN … CASCADE` and any other `DROP … CASCADE`, which also drop the columns that depend on them, and PostgreSQL `DROP OWNED` | | `unreadable` | SQL the guard cannot read: an unterminated string, comment or body, and SQL built at run time (`EXECUTE` of a concatenation or `format()`, `PREPARE … FROM @variable`) | The guard reads the SQL as the database will: MySQL's backslash escapes and `#` comments, PostgreSQL's `E'…'` strings and dollar-quoted bodies. The dialect comes from the factory at boot and from `snapshot.json` elsewhere; where neither names one, every dialect's reading counts. Statements inside a `CREATE PROCEDURE`, `FUNCTION` or `TRIGGER` body, and a function body written as a string, are judged like any other. A rename loses no rows, but the previous deploy keeps reading the old name until it is replaced. A type change that only widens (a longer `varchar`, `smallint` to `integer`) passes when the `snapshot.json` drizzle-kit writes beside each migration shows both types; without that evidence it is reported. A statement against a table that an earlier pending migration creates is never reported, so a fresh database, which applies the whole history at once, is not refused over an old drop. To apply a destructive migration, acknowledge it on the first line of its `migration.sql`, with the reason a reviewer should read: ```sql -- guren:allow-destructive: posts moved to articles in 20261012_copy_posts DROP TABLE "posts"; ``` Keep the comment on the first line. drizzle splits the file at `--> statement-breakpoint`, and a comment alone after the last one is an empty statement that SQLite rejects. Where the guard applies: - `bunx guren db:migrate` refuses an unacknowledged statement in every environment. `--dry-run` reports without applying, and `--allow-destructive` applies once without editing the file. - At boot, the factory option decides. `destructiveMigrations: 'refuse'`, which new apps set in `config/database.ts`, throws before anything is applied; `'warn'`, the default for apps that do not set it, prints the statements and applies them. `GUREN_ALLOW_DESTRUCTIVE_MIGRATIONS=1` lets one refused run through. A `db:reset` re-applies everything into an emptied database and is never judged. - `bunx guren check` and `bunx guren gate` report the migrations not yet on `main` (committed on the branch, uncommitted or untracked), so the agent's Stop hook and CI catch one before it is merged. A drop that already shipped is never reported. ```ts const database = createPostgresDatabase({ migrationsFolder: new URL('../db/migrations', import.meta.url), destructiveMigrations: 'refuse', }) ``` The comment records that a person decided the data can go; an agent can type it as easily as the statement, so the harness tells it to ask first, and review is where a reason that does not hold up gets caught. ## Seeding Seeders live in `db/seeders/`. The simplest one exports an async `run()` function; this one uses the `Post` model described in [Defining Models](./models.md#defining-models): ```ts // db/seeders/PostsSeeder.ts import { Post } from '@/app/Models/Post' export async function run() { await Post.create({ title: 'Hello', body: 'Welcome to Guren!' }) } ``` `bun run db:seed` runs every seeder: ```bash bun run db:seed ``` ### Seeding through Drizzle `defineSeeder()` hands the seeder the Drizzle database itself, which is useful for bulk inserts and upserts that bypass the model layer. Its type depends on the dialect, so annotate the context with `AppSeederContext`, the alias `config/database.ts` exports for whichever database the app is configured with: ```ts // db/seeders/PostsSeeder.ts import { defineSeeder } from '@guren/core' import type { AppSeederContext } from '../../config/database.js' import { posts } from '../schema.js' export default defineSeeder(async ({ db }: AppSeederContext) => { await db.insert(posts).values({ title: 'Hello', body: 'Welcome to Guren!' }) }) ``` `SeederContext` without a type argument means PostgreSQL, so on MySQL or SQLite it rejects the app's own schema. `AppSeederContext` is exported by `config/database.ts` in apps scaffolded from this release onwards; an older app imports its dialect's alias from `@guren/core` directly instead, one of `PostgresSeederContext`, `MySqlSeederContext`, `SqliteSeederContext`, or `AwsDataApiSeederContext`: ```ts import { defineSeeder, type MySqlSeederContext } from '@guren/core' ``` > [!NOTE] > D1 has no seeder context: its `seedDatabase()` does not run seeders. Seed a D1 > database with `wrangler d1 execute --file ` instead. ## Next Steps - [Models](./models.md): define a model on a table, then query, create and update its rows - [Relationships](./relationships.md): declare relations between models and eager-load them --- # Models A model wraps one table from `db/schema.ts`. It queries the table, creates and updates rows, and decides how a record is cast, serialized and paginated. The connection and the schema are set up in [Database](./database.md), and relations between models are declared as described in [Relationships](./relationships.md). ## Defining Models Use `defineModel()` to derive a typed model directly from a Drizzle table: ```ts // app/Models/Post.ts import { defineModel } from '@guren/core' import { posts } from '@/db/schema' export type PostRecord = typeof posts.$inferSelect export type NewPostRecord = typeof posts.$inferInsert export class Post extends defineModel(posts) {} ``` That is all you need. `Post` now has `find`, `create`, `where`, `paginate`, and dozens more methods. ### Reshaping the create payload The type `defineModel()` infers for `create()` requires every column without a database default. When the model derives a column itself, say so in the same call rather than hand-writing a type: ```ts export class User extends defineModel(users, { base: AuthenticatableModel, optionalOnCreate: ['passwordHash'], // derived from `password`, so callers need not pass it requireOnCreate: ['password'], // demand the virtual field instead }) {} ``` `optionalOnCreate` makes columns optional: they keep their type, callers just need not supply them. `requireOnCreate` goes the other way, and accepts both table columns (Drizzle marks defaulted ones optional) and fields contributed by `base`. Both are type-level only and are checked against the real keys, so a typo fails to compile. Neither closes the payload: a create type always admits unknown keys as `unknown`, so `fillable` remains what rejects an unwanted field at runtime. ## Querying Data Start simple, then build up: ```ts // Fetch everything const allPosts = await Post.all() // Find by primary key const post = await Post.find(1) // returns null if missing const post = await Post.findOrFail(1) // throws ModelNotFoundException (404) if missing // First matching record const latest = await Post.first() ``` ### Fluent QueryBuilder Chain conditions, ordering, and limits for more complex queries: ```ts const published = await Post.where('status', 'published').get() const trending = await Post.where('status', 'published') .where('views', '>', 100) .orWhere('featured', true) .orderBy('createdAt', 'desc') .limit(10) .get() // Object syntax for simple equality const drafts = await Post.where({ status: 'draft', authorId: 1 }).get() // Callback syntax groups conditions in parentheses: // (title LIKE ? OR excerpt LIKE ?) AND status = 'published' const hits = await Post.where((q) => { q.where('title', 'like', '%bun%').orWhere('excerpt', 'like', '%bun%') }) .where('status', 'published') .get() ``` > [!TIP] > The QueryBuilder is thenable -- you can `await` it directly without calling `.get()`. Both `await Post.where({ status: 'draft' })` and `await Post.where({ status: 'draft' }).get()` produce the same result. | Method | Description | |--------|-------------| | `.where(column, value)` | Filter by equality | | `.where(column, op, value)` | Filter with an operator: `'='`, `'!='`, `'>'`, `'<'`, `'>='`, `'<='`, `'like'`, `'in'`, `'not in'`, `'is null'`, `'is not null'` | | `.where(object)` | Filter by multiple equalities | | `.where(callback)` | Parenthesized condition group, AND-ed with the rest | | `.orWhere(column, value)` | OR condition | | `.orWhere(column, op, value)` | OR condition with an operator | | `.orWhere(callback)` | OR a parenthesized condition group | | `.orderBy(column, direction?)` | Sort results | | `.limit(n)` / `.offset(n)` | Limit and skip | | `.get()` | Execute and return array | | `.first()` | Return first result or null | | `.count()` | Return count of matching records | | `.sum(column)` / `.avg(column)` | Sum or average of a column over matching records | | `.min(column)` / `.max(column)` | Smallest or largest value of a column | | `.exists()` | Whether any record matches | | `.increment(column, amount?)` / `.decrement(column, amount?)` | Add to or subtract from a column in one `UPDATE` | | `.toDrizzle(query?)` | A Drizzle select that carries the model's conditions and scopes | ### Aggregates ```ts const revenue = await Order.where('status', 'paid').sum('total') const averageViews = await Post.where('status', 'published').avg('views') const newest = await Post.newQuery().max('createdAt') const hasDrafts = await Post.where('status', 'draft').exists() ``` Aggregates run through the model's [global scopes](#global-scopes), so a model with [`SoftDeletes`](#soft-deletes) leaves trashed rows out of a sum just as it leaves them out of `get()`. The result keeps the column's type. An `integer` or `real` column sums to a `number`, a `bigint({ mode: 'bigint' })` column to a `bigint`, and a `numeric` or `decimal` column to a `string`, which is how Drizzle types those columns so that no digit is lost. `avg()` returns a `number` for a `number` column and a decimal string otherwise. When nothing matches, `sum()` returns the zero of that type (`0`, `0n` or `'0'`) and the other three return `null`. Like `count()`, aggregates ignore `limit()` and `offset()`. A sum of a `number` column past `Number.MAX_SAFE_INTEGER` throws instead of rounding. Declare that column with `mode: 'bigint'`. ### Dropping to Drizzle `toDrizzle()` hands a query to Drizzle with the model's conditions and global scopes already in its `WHERE` clause. Use it for joins, custom selections, and anything else the builder cannot express: ```ts import { getDatabase } from '@/config/database' import { posts, users } from '@/db/schema' import { desc, eq, gt } from 'drizzle-orm' const db = await getDatabase() const rows = await Post.where('status', 'published') .toDrizzle( db.select({ id: posts.id, title: posts.title, author: users.name }) .from(posts) .leftJoin(users, eq(posts.authorId, users.id)), ) .where(gt(posts.views, 100)) .orderBy(desc(posts.id)) ``` - Without an argument, `toDrizzle()` starts from `select().from(table)` and runs inside the open transaction when there is one. A query you pass runs on the handle you built it from, so inside [`Model.transaction()`](#transactions) build it from `trx`. - A `.where()` on the result is AND-ed with the model's conditions and cannot drop a scope. To pass a query that already has a `where()`, call `$dynamic()` before it. - The builder's `orderBy()`, `limit()` and `offset()` carry over. `select()` carries over only without an argument, since a query you pass keeps its own selection. - Rows come back as Drizzle reads them. Casts, accessors and eager loads do not apply. - `toSql()` returns the same conditions as one `SQL` fragment for a query you assemble yourself. On a plain Drizzle select a second `.where()` replaces the first, so combine the fragment with `and()`: ```ts const popular = await db.select().from(posts).where(and(Post.newQuery().toSql(), gt(posts.views, 100))) ``` A query written against `db` alone never goes through the model and applies none of its scopes. `Model.query()` returned exactly that kind of query and is deprecated for this reason (see [Upgrading](./upgrading.md)). > [!TIP] > To use Drizzle's relational queries (`db.query.
.findMany(...)`), pass a `relations` option built with `defineRelations(schema, ...)` from `drizzle-orm` (RQB v2). The `Model` API in Guren does not require this. ## Creating and Updating ```ts // Create const post = await Post.create({ title: 'Hello World', body: 'Welcome to Guren!', }) // Update await Post.update({ id: post.id }, { title: 'Updated Title' }) // Delete await Post.delete({ id: post.id }) ``` Bulk `update()`, `forceUpdate()`, and `delete()` reject `limit()`, `offset()`, and `orderBy()`. Select the intended IDs first, then write with `whereIn()`. On a `SoftDeletes` model, builder `delete()` also marks rows deleted; use `forceDelete()` for permanent removal. ### Incrementing a column `increment()` and `decrement()` add to a numeric column inside the database, in a single `UPDATE`: ```ts await Post.increment({ id: post.id }, 'views') await Product.decrement({ id: product.id }, 'stock', 2) ``` Reading a value, adding to it in the controller and writing it back loses counts when two requests overlap. Here the database does the addition, so every call counts. A counter kept in a GET action also counts `HEAD` requests and Inertia prefetches unless the action guards it: see [Writes in a GET Action](./controllers.md#writes-in-a-get-action). Both resolve to the number of rows they changed, so a condition works as a guard: ```ts const taken = await Product.where({ id: product.id }) .where('stock', '>=', quantity) .decrement('stock', quantity) if (taken === 0) { // Not enough stock. Nothing was written. } ``` - The amount defaults to `1`. A `numeric` or `decimal` column also takes a decimal string such as `'10.50'`, which PostgreSQL and MySQL add exactly. SQLite stores such a column as a floating-point number. - A column that is not numeric is refused, and so is a fractional amount on an integer column. - [Global scopes](#global-scopes) apply as they do to `update()`. `fillable`, mutators, and [hooks](#model-hooks) do not run, since the column is named in your code and no request data is written. - A `NULL` stays `NULL`. Declare a counter column with `.notNull().default(0)`. - On a builder, `limit()`, `offset()`, and `orderBy()` are rejected, as for the other bulk writes. ### Transactions Use `Model.transaction()` when multiple writes must succeed or fail together: ```ts await Post.transaction(async (trx) => { const post = await Post.create({ title: 'Atomic write', body: 'Everything in one transaction', }, { trx }) await Post.update({ id: post.id }, { status: 'published' }, { trx }) }) ``` If an error is thrown in the callback, Guren rolls back the transaction. The second argument to the callback is a transaction-bound copy of the model, which passes `{ trx }` for you: ```ts await Post.transaction(async (_trx, txPost) => { const post = await txPost.create({ title: 'Scoped write', body: 'No manual { trx } forwarding', }) await txPost.update({ id: post.id }, { status: 'published' }) }) ``` Things to know: - **A call without `{ trx }` still joins the transaction.** Inside the callback, a model call that leaves the handle off runs on the open transaction instead of going to the pool, where a single-connection pool would make it wait on the transaction that owns the connection. - **A nested `Model.transaction()` is a savepoint.** Its writes commit or roll back with the outer transaction, and an inner error the outer callback catches discards only the inner writes. Await each nested transaction before starting the next: savepoints on one connection are released in the order they were taken, so two running at once discard each other's frames. - **On SQLite, transactions run one at a time.** SQLite holds a single connection, so concurrent transactions are queued, each committing or rolling back on its own. Model reads and writes made outside a transaction wait until it settles, and so does awaiting `toDrizzle()` without an argument. Its synchronous `.all()`, `.get()`, `.run()` and `.values()` cannot wait, so they throw while another request holds a transaction open. A Drizzle query you build on `db` yourself does not wait and would run inside that transaction; await the transaction first. ### Mass Assignment Protection Control which fields can be set through `create()` and `update()`: ```ts export class Post extends defineModel(posts, { // Allowlist — only these fields are assignable. // Checked against the table's columns: a typo is a compile error. fillable: ['title', 'body', 'status'], }) {} ``` The same allowlist can be declared as `static fillable = ['title', 'body', 'status']` on the class instead; the option form is preferred because TypeScript verifies every name against the table (a `static` declaration on the subclass shadows the option). When `fillable` is set, passing any field outside the allowlist to `create()` or `update()` throws a `MassAssignmentException` (exported from `@guren/core`). The message names the blocked fields, so a typo or an injection attempt fails loudly at the call site instead of being silently discarded and resurfacing later as a confusing NOT NULL violation: ```ts await Post.create({ title: 'Hello', body: '...', status: 'draft', authorId: 1 }) // MassAssignmentException: Post: mass assignment blocked for field(s) "authorId" ``` #### Columns the server chooses Some columns belong in the row but must never come from a request: the post's author, the post a comment belongs to, a default status. Keep them out of `fillable` and pass them in the `set` option, beside the validated data: ```ts const author = await this.auth.userOrFail() const data = await this.validateBody(PostPayloadSchema) const post = await Post.create(data, { set: { authorId: author.id } }) await Post.update({ id: post.id }, data, { set: { status: 'draft' } }) ``` The query builder's bulk update takes the same option: `Post.where('status', 'draft').update(data, { set: { reviewedAt: new Date() } })`. `data` is still filtered by `fillable`; only the keys in `set` skip it. Because `set` exists to keep the two apart, it throws a `MassAssignmentException` when: - a `set` key is in `fillable` (a request could already set it, so it belongs in `data`); - `data` carries a key that `set` also sets; - a `set` key is `id` or a credential column; - the model declares no `fillable`. `{ set: { ...data, authorId } }` usually throws under the first rule, because the spread moves fillable keys into `set`. It does not when the spread carries no fillable key, so do not rely on the throw: never spread request input into `set`. `guren audit` warns on a spread written inside a `set` literal (`set-spread:*`). #### Force writes For writes that carry no request data at all (OAuth account linking, seeders, system records), bypass the allowlist with `forceCreate()` / `forceUpdate()`: ```ts const user = await User.forceCreate({ name: profile.name, email: profile.email, passwordHash: `oauth:${provider}:${profile.id}`, }) await User.forceUpdate({ id: user.id }, { emailVerifiedAt: new Date() }) ``` > [!WARNING] > `forceCreate()` / `forceUpdate()` skip mass-assignment protection entirely. Never pass request input to them, validated or not: to add a server-chosen column to request data, use `set`. Two protections apply regardless of `fillable`: - The primary key (`id`) is always silently stripped from mass-assignment input — a form that round-trips it cannot retarget the write. - On models extending `AuthenticatableModel`, credential columns (the password hash and remember token) always throw. Listing them in `fillable` does not open them; pass a plain `password` and let the model hash it, or use `forceCreate()`/`forceUpdate()` for trusted server-side values. > [!NOTE] > If `fillable` is not set, all columns except `id` and the denied credential columns are assignable. Declare it on any model that accepts user input. ## Query Scopes Scopes encapsulate common filters so you can reuse them by name: ```ts export class Post extends defineModel(posts) { static scopes = { published: (q: QueryBuilder) => q.where('status', 'published'), popular: (q: QueryBuilder) => q.where('views', '>', 1000), recent: (q: QueryBuilder) => q.orderBy('createdAt', 'desc').limit(10), } } ``` Apply them with `.scope()`, chained with each other or with any other condition: ```ts const trending = await Post.scope('published').scope('popular').get() const myPopular = await Post.scope('published') .where('authorId', currentUser.id) .get() ``` ## Global Scopes Global scopes apply automatically to every query on a model. Use them for multi-tenancy, soft deletes, or any filter that should always be active. ```ts // Always filter by the current tenant User.addGlobalScope('tenant', (q) => q.where('tenantId', currentTenantId())) // Always exclude inactive users User.addGlobalScope('active', (q) => q.where('active', true)) ``` Every query entry point applies both scopes automatically: `all()`, `find()`, `first()`, `where()` and its `whereIn`/`whereNull`/`select` siblings, `scope()`, `orderBy()`, `paginate()` (the count as well as the rows), `newQuery()`, and the queries that eager-load a relation, which apply the *related* model's scopes. Writes honor them too: `update()`, `forceUpdate()`, and `delete()` add the same scopes to their `where`, so a `tenant` scope stops one tenant from updating or deleting another tenant's row, not just from reading it. The only way past them is to ask explicitly, below. ### Bypassing Global Scopes Remove a specific scope for one query: ```ts const allUsers = await User.withoutGlobalScope('active').get() ``` Remove all global scopes: ```ts const everyone = await User.withoutGlobalScopes().get() ``` Remove a scope permanently: ```ts User.removeGlobalScope('active') ``` > [!TIP] > The `SoftDeletes` mixin registers a global scope named `'softDelete'`. `withTrashed()` *is* `withoutGlobalScope('softDelete')`: either spelling reaches trashed rows while every other global scope stays applied, so a `tenant` scope keeps isolating them. `withoutGlobalScopes()` is the one that drops those too. ## Model Hooks Hooks run logic at specific points in a record's lifecycle. Use them for auto-generated slugs, timestamps, audit logs, or cache invalidation: ```ts import { slugify } from '@/app/utils/string' export class Post extends defineModel(posts) { static hooks = { creating: async (data) => { data.slug = slugify(data.title) }, updating: async (data) => { data.updatedAt = new Date() }, deleted: async (data) => { console.log('Post deleted:', data.id) }, } } ``` | Hook | Timing | |------|--------| | `creating` / `created` | Before / after insert | | `updating` / `updated` | Before / after update | | `deleting` / `deleted` | Before / after delete | | `saving` / `saved` | Before / after both insert and update | ## Model Observers When hook logic grows complex, extract it into a dedicated observer class. Observers respond to the same lifecycle events as hooks but live in their own file. ```ts // app/Observers/PostObserver.ts import type { ModelObserver, PlainObject } from '@guren/core' export class PostObserver implements ModelObserver { creating(data: PlainObject) { data.slug = slugify(data.title as string) } async created(data: PlainObject) { await notifySubscribers(data) } async deleting(data: PlainObject) { await clearPostCache(data.id) } } ``` Register the observer on the model: ```ts import { PostObserver } from '@/app/Observers/PostObserver' Post.observe(PostObserver) ``` Returning `false` from a before-event (`creating`, `updating`, `deleting`, `saving`) aborts the operation, just like inline hooks. Observers and inline hooks coexist: hooks fire first, then observers. ## Soft Deletes Instead of permanently removing records, soft deletes set a `deletedAt` timestamp. Users can recover deleted content, and queries automatically exclude trashed records. ```ts import { SoftDeletes, defineModel } from '@guren/core' import { posts } from '@/db/schema' export class Post extends SoftDeletes(defineModel(posts)) {} ``` ```ts await Post.delete({ id: 1 }) // Sets deletedAt on a live row (the row remains) const active = await Post.all() // Excludes soft-deleted const all = await Post.withTrashed().get() // Includes soft-deleted const trashed = await Post.onlyTrashed().get() await Post.restore({ id: 1 }) // Clears deletedAt await Post.forceDelete({ id: 1 }) // Permanent removal ``` Every one of these honors the model's *other* global scopes. `delete()` marks only a live row the current scopes can see — on an already-trashed row it matches nothing and leaves the original `deletedAt` alone. `restore()` and `forceDelete()` drop the `softDelete` filter so they reach trashed rows, and keep the rest: a `tenant` scope still stops a force delete, which cannot be undone, from reaching another tenant's row. Inside a transaction, every one of them takes the handle. The transaction-bound scope covers `delete()`; the rest take it as a trailing argument, like any other write: ```ts await Post.transaction(async (trx, txPost) => { await txPost.delete({ id: 1 }) await Post.restore({ id: 2 }, { trx }) await Post.forceDelete({ id: 3 }, { trx }) const trashed = await Post.onlyTrashed({ trx }).get() }) ``` > [!TIP] > Your schema must include a `deletedAt` timestamp column for soft deletes to work. ## Attribute Casting Automatically convert column values when reading from the database: ```ts export class Post extends defineModel(posts) { static casts = { metadata: 'json', // JSON string -> object publishedAt: 'date', // string -> Date isActive: 'boolean', // 0/1 -> true/false viewCount: 'number', // string -> number } } ``` The cast types are `'json'`, `'date'`, `'boolean'`, `'number'` and `'string'`. ## Accessors & Mutators Accessors compute virtual attributes when reading records. Mutators transform values before writing to the database. ### Accessors Define computed properties that are automatically applied when records are fetched: ```ts export class User extends defineModel(users, { accessors: { // `record` is typed as the table's record — field typos are compile errors fullName: (record) => `${record.firstName} ${record.lastName}`, isAdmin: (record) => record.role === 'admin', }, }) {} ``` (`static accessors = { ... }` on the class works too, without the typed `record` parameter.) ```ts const user = await User.find(1) console.log(user.fullName) // "John Doe" console.log(user.isAdmin) // true ``` Accessors run on every read path: `all()`, `find()`, `where()`, `first()`, and `paginate()`. ### Mutators Transform input data before it hits the database: ```ts export class User extends defineModel(users) { static mutators = { email: (value) => String(value).toLowerCase().trim(), name: (value) => String(value).trim(), } } ``` ```ts await User.create({ email: ' JOHN@EXAMPLE.COM ', name: ' John ' }) // Stored as: email = "john@example.com", name = "John" ``` Mutators run on both `create()` and `update()`, before hooks and before cast serialization. ## Serialization Control how model records appear in API responses and Inertia props. ### Hiding Fields Exclude sensitive fields from serialized output: ```ts export class User extends defineModel(users, { hidden: ['passwordHash', 'rememberToken'], }) {} ``` Like `fillable`, the option is checked against the table's columns; `static hidden = [...]` also works. ```ts const user = await User.find(1) const json = User.serialize(user) // { id: 1, name: "John", email: "john@example.com" } // passwordHash and rememberToken are excluded ``` Fields listed in `hidden` are also stripped from the record returned by `auth.user()`, so they never leak into Inertia shared props or API responses that expose the authenticated user. See the [Authentication guide](./authentication.md) for details. ### Visible Fields Use a whitelist instead of a blacklist: ```ts export class User extends defineModel(users, { visible: ['id', 'name', 'email'], }) {} ``` When `visible` is set, only those fields appear. `visible` takes precedence over `hidden`. ### Appending Virtual Attributes Include accessor-computed values in serialized output: ```ts export class User extends defineModel(users, { accessors: { fullName: (record) => `${record.firstName} ${record.lastName}`, }, appends: ['fullName'], hidden: ['firstName', 'lastName'], }) {} ``` `appends` may only name accessors declared in the same options object: an undeclared name is a compile error. ```ts const json = User.serialize(user) // { id: 1, fullName: "John Doe", email: "john@example.com" } ``` ### Serializing Collections ```ts const users = await User.all() const json = User.serializeMany(users) ``` > [!TIP] > `serialize()` and `serializeMany()` are ideal for building Inertia page props or API responses. Pair them with `JsonResource` for more complex transformations. ## Pagination Paginate query results and get metadata for building page controls: ```ts const result = await Post.paginate({ page: 1, perPage: 10 }) // result.data — PostRecord[] for the current page // result.meta — { total, perPage, currentPage, totalPages, hasMore, from, to } ``` Pass pagination data directly to an Inertia page: ```ts import { Controller, paginate, type PaginatedPageProps } from '@guren/core' import { PostResource, type PostResourceData } from '@/app/Http/Resources/PostResource' import { pages } from '@/.guren/pages.gen' type PostsIndexProps = PaginatedPageProps async index() { const page = Number(this.query('page', '1')) const result = await Post.scope('published').paginate({ page, perPage: 15 }) const paginator = paginate(result, { path: this.request.path ?? '/posts' }) return this.inertia(pages.posts.Index, { data: result.data.map((post) => new PostResource(post).toJSON()), pagination: { meta: paginator.meta(), links: paginator.links(), }, } satisfies PostsIndexProps) } ``` --- # Relationships Declare relationships next to the model that owns them, then eager-load them everywhere. Each relation is registered on the model class with `hasMany()`, `belongsTo()` or one of the other methods below. The models themselves are described in [Models](./models.md). ## hasMany / belongsTo ```ts // app/Models/User.ts export class User extends defineModel(users) { static override relationTypes: { posts: HasManyRecord } = { posts: [], } } User.hasMany('posts', () => import('./Post.js').then((m) => m.Post), 'authorId', 'id') // app/Models/Post.ts export class Post extends defineModel(posts) { static override relationTypes: { author: BelongsToRecord } = { author: null, } } Post.belongsTo('author', () => import('./User.js').then((m) => m.User), 'authorId', 'id') ``` `relationTypes` tells TypeScript what each relation loads as; the values (`[]`, `null`) are runtime placeholders. [Typing loaded relations](#typing-loaded-relations) shows the `declare` form that needs none. The related model is passed as a function that imports it, so two models can refer to each other without a circular import. ## Other relationship types ```ts import { userRoles } from '@/db/schema' User.hasOne('profile', Profile, 'userId', 'id') User.belongsToMany('roles', Role, userRoles, 'userId', 'roleId') Country.hasManyThrough('posts', Post, User, 'countryId', 'authorId') ``` | Method | Arguments | |--------|-----------| | `hasMany(name, Related, foreignKey, localKey)` | The foreign key on the related table, and this model's key it points at (usually `id`). Loads an array, `[]` when nothing matches | | `belongsTo(name, Related, foreignKey, ownerKey)` | The foreign key on this model, and the related model's key. Loads one record or `null` | | `hasOne(name, Related, foreignKey, localKey)` | As `hasMany`, but loads one record or `null` | | `belongsToMany(name, Related, pivotTable, foreignPivotKey, relatedPivotKey, parentKey?, relatedKey?)` | Many-to-many through a pivot table | | `hasManyThrough(name, Related, Through, firstKey, secondKey)` | Records reached through an intermediate model | | `morphMany(name, Related, morphName, localKey)` / `morphTo(name, morphName)` | Polymorphic relations, below | For `belongsToMany`, `pivotTable` is the Drizzle table object exported from `@/db/schema`, not the table's name. `foreignPivotKey` and `relatedPivotKey` are both columns *on the pivot*, referencing this model and the related one; `parentKey` and `relatedKey` are the local keys they point at, and both default to `'id'`. ## Polymorphic Relationships Polymorphic relationships let a model belong to more than one type of parent using a single relation. For example, both posts and videos can have comments. Define the type/id columns on the related table: ```ts // db/schema.ts export const comments = pgTable('comments', { id: serial('id').primaryKey(), body: text('body').notNull(), commentableType: text('commentable_type').notNull(), commentableId: integer('commentable_id').notNull(), }) ``` Register the relationships: ```ts // Parent models Post.morphMany('comments', Comment, 'commentable', 'id') Video.morphMany('comments', Comment, 'commentable', 'id') // Child model (inverse) Comment.morphTo('commentable', 'commentable') // Map type strings to model classes Model.morphMap = { 'Post': Post, 'Video': Video, } ``` Query them like any other relation: ```ts const postWithComments = await Post.with('comments') const comment = await Comment.findWith(1, 'commentable') console.log(comment.commentable) // Post or Video record ``` ## Eager Loading ```ts const users = await User.with('posts') // users[0].posts is PostRecord[] const posts = await Post.with('author') // posts[0].author is UserRecord | null const filtered = await Post.with('author', { authorId: [1, 2] }) ``` Eager loading also works on the QueryBuilder, so you can combine it with filters and ordering. The record-returning methods (`get()`, `first()`, `firstOrFail()`, and `paginate()`) all attach the relations: ```ts const activeUsers = await User.where('active', true) .with('posts') .orderBy('name') .get() const user = await User.newQuery().with('posts').first() // Each row of the page carries its author const page = await Post.newQuery().with('author').orderBy('id', 'desc').paginate({ page: 1, perPage: 10 }) ``` ### Nested relations Nested relations use dot notation: ```ts const users = await User.with('posts.comments') ``` Several paths may branch off the same relation. The shared head is read once, so every branch lands on the same records: ```ts const users = await User.newQuery().with('posts.comments', 'posts.tags').get() users[0].posts[0].comments // loaded users[0].posts[0].tags // loaded too ``` ### Constraining what loads On the QueryBuilder, the object form of `with()` takes a callback per relation to constrain the query that loads it. The callback receives that relation's query builder with the foreign-key filter already on it, so a `where()` narrows which related rows load: ```ts const users = await User.newQuery() .with({ posts: (q) => q.where('published', true) }) .get() users[0].posts // only the published posts ``` Each object key constrains exactly the level it names, and the order of the keys does not matter. A dotted key constrains the leaf and leaves the head unfiltered; list both keys to constrain both levels: ```ts // `posts` loads unfiltered, `comments` are filtered await User.newQuery() .with({ 'posts.comments': (q) => q.where('approved', true) }) .get() // both levels filtered await User.newQuery() .with({ posts: (q) => q.where('published', true), 'posts.comments': (q) => q.where('approved', true), }) .get() ``` > [!WARNING] > A top-level `orWhere()` inside a callback **widens** the query instead of > narrowing it, because it ORs against the foreign-key filter the loader > applied. Keep it grouped: > `q.where((g) => g.where('a', 1).orWhere('b', 2))`. > > A `select()` must include the column the relation is keyed on (the foreign > key for `hasMany`/`hasOne`, the owner key for `belongsTo`). Without it the > loader cannot match rows back to their parent and the relation loads empty. > [!NOTE] > Relations are loaded in batches rather than one query per parent, so `limit()` > inside a constraint caps the whole result set, not each parent's share. A > constraint carrying `limit()`, `offset()` or `orderBy()` is answered by one > query over every key at once; without one, the keys are split into batches the > driver's parameter limit admits. For `belongsToMany` and `hasManyThrough` the > keys split that way are the related rows', not the parents'. For `morphTo`, the > callback runs once per morph target, so it may only reference columns every > target shares. For `belongsToMany` and `hasManyThrough`, the callback constrains the query for the **related** model, not the pivot or through-table lookup that finds which rows to fetch. Filter on the related model's own columns: ```ts // keeps the `news` tags of each post; the pivot lookup is untouched await Post.newQuery() .with({ tags: (q) => q.where('label', 'news') }) .get() ``` The static `Model.with()` is a different signature: its second argument filters the *parent* records, not the relation. Use `Model.newQuery().with({ ... })` for constraint callbacks. ### Typing loaded relations Nested paths type only the head segment from `relationTypes`. To get typed children, declare the nested shape inside the head relation's record type: ```ts export class User extends defineModel(users) { declare static relationTypes: { posts: HasManyRecord } } const loaded = await User.with('posts.comments') loaded[0].posts[0].comments // CommentRecord[] — typed end to end ``` > [!NOTE] > Only the head segment (`posts` above) is checked against `relationTypes`: anything after the first dot is an unvalidated string, so a typo'd or malformed tail (`'posts.'`, `'posts..comments'`, `'posts.typo'`) still compiles. At runtime, an unknown tail relation throws, but only once the loader actually has a loaded row to recurse into. If every record's head relation loads zero rows, the tail is never inspected and the call quietly no-ops instead of throwing. Nesting through a `morphTo` relation always throws at runtime regardless. That constraint isn't enforced at the type level either. `BelongsToRecord` is always `T | null` — the loader cannot know the row exists. When the foreign key is `NOT NULL` and the parent is guaranteed, declare the relation with `BelongsToRequiredRecord` instead. Using the `declare` modifier skips the runtime placeholder value: ```ts export class Comment extends defineModel(comments) { declare static relationTypes: { author: BelongsToRequiredRecord } } const comments = await Comment.with('author') comments[0].author.name // no null check required ``` ## Relation Counts `withCount()` attaches a `${name}Count` field without loading the related rows, ideal for list pages that only display totals: ```ts const users = await User.withCount('posts') // users[0].postsCount is number const posts = await Post.withCount(['comments', 'author'], { published: true }) ``` Supported for `hasMany`, `hasOne`, `morphMany` (children per record) and `belongsTo` (0 or 1). --- # Frontend Guide Guren delivers a single-page application experience by combining Inertia.js with React. Controllers return Inertia responses, and the frontend renders the matching React components located under `resources/js/pages/`. For the parts of the Inertia protocol the server implements, see [Inertia Protocol Support](./inertia.md). ## Project Structure - `resources/js/app.tsx`: Bootstraps the Inertia app and registers global providers. - `resources/js/ssr.tsx`: Exports the server-side renderer consumed by the backend when SSR is enabled. - `resources/js/pages/`: React components that map to controller responses. - `resources/js/components/`: Shared UI components (optional but recommended). - `resources/css/app.css`: Tailwind (or your chosen CSS) entry point. ## Page Components Page filenames map to the page definitions auto-generated in `.guren/pages.gen.ts`. Props are defined as `interface Props` in each page component and extracted by codegen: ```ts // Controller return this.inertia(pages.posts.Index, { data, pagination, }) ``` ```tsx // resources/js/pages/posts/Index.tsx import type { PageProps } from '@guren/inertia-client/contracts' import { Head, Link } from '@inertiajs/react' import { pages } from '@/.guren/pages.gen' type Props = PageProps export default function Index({ data, pagination }: Props) { return ( <>
{data.map((post) => (

{post.title}

{post.excerpt}

Read more
))}

{pagination.meta.total} posts

) } ``` Use TypeScript to annotate props so you benefit from compile-time safety. ## Layouts and Shared UI Wrap pages with layout components to keep navigation and shared UI consistent: ```tsx // resources/js/components/Layout.tsx export function Layout({ children }: React.PropsWithChildren) { return (
{children}
) } ``` ```tsx // resources/js/pages/posts/Index.tsx import { Layout } from '@/resources/js/components/Layout' export default function Index({ posts }: Props) { return ( {/* page content */} ) } ``` ### UI components `bunx guren add ui` copies a small set of token-styled components into `resources/js/components/ui/` (`Button`, `Label`, `Input`, `Textarea`, `Select`, `Checkbox`, `Field`, `Card`, `Alert`), and the pages `make:feature` and `make:auth` write import them. The files belong to the app: change the focus ring in `Input.tsx` or the padding in `Button.tsx`, and every page that imports them follows. ```tsx import { Button } from '@/resources/js/components/ui/Button' import { Input } from '@/resources/js/components/ui/Input' import { Label } from '@/resources/js/components/ui/Label' ``` `Field` wires one form key. It reads the route's form contract from `.guren/forms.gen.ts`, which `guren codegen` writes for every named POST, PUT, PATCH or DELETE route whose body schema is an object, and renders the label, a control carrying the `required`, length and range limits the validator declares, and the server's error under it. The New and Edit pages `make:feature` writes use it: ```tsx import { useRouteForm } from '@guren/inertia-client/forms' import { postsStoreForm } from '@/.guren/forms.gen' import { Button } from '@/resources/js/components/ui/Button' import { Field } from '@/resources/js/components/ui/Field' const form = useRouteForm(postsStoreForm, { title: '', body: '' })
``` `method="post"` and `action` cover a submit made before the page hydrates. The browser then sends a plain POST, which the server refuses since it carries no CSRF token, but the fields, the password included, stay out of the URL instead of riding in a GET query string. The user sees a 419 "Page Expired" page asking them to reload and submit again. HTML forms send only GET and POST, so a PUT or PATCH form still says `post`. For a path with parameters, build the action with `resolveRouteUrl(postsUpdateForm.path, { id: post.id })` from `@guren/inertia-client/forms`. The label defaults to a [translation](./i18n.md#form-labels) when the app has one, else the field name as words (`startsAt` reads "Starts at"). Pass `label` to change it, and `as` for an input the schema cannot express (`textarea`, `password`, `file`). `Field` and `useRouteForm` need an `@guren/inertia-client` that exports `/forms`. See [`add ui`](./cli.md#add-ui) for re-running, `--diff` and `--force`. The Dev Center's [Components page](./application-diagnostics.md#components) renders each copy in every variant and state, and shows which copies differ from their template. ## Forms and Navigation Inertia provides helpers for client-side navigation and form submissions: - `Create Post` for navigation without a full reload. - `const form = useForm({ title: '', body: '' })` to manage form state. - `form.post('/posts')` to submit data. Handle validation errors by returning them from the controller and reading `form.errors` on the client. ## Partial Reloads A visit back to the page a user is already on does not have to refetch every prop. The client names the props it wants with the `only` or `except` visit options, and the server sends only those: ```tsx import { router } from '@inertiajs/react' router.reload({ only: ['users'] }) router.visit('/users?active=true', { except: ['companies'] }) ``` The request carries the current component name in `X-Inertia-Partial-Component`, so the filter applies only while the response renders that same component. A visit that ends up on another page (a redirect to the login page, say) receives the full prop set. Shared props are filtered the same way, and `errors` is sent on every response. A prop passed as a function is evaluated only when it is sent, so a partial reload that leaves it out never runs its query: ```typescript import { Controller } from '@guren/core' import { pages } from '@/.guren/pages.gen' export class UserController extends Controller { async index() { return this.inertia(pages.users.Index, { users: () => User.all(), companies: () => Company.all(), }) } } ``` The page component still declares `users: User[]`. The controller call is checked against the resolved type, and `ControllerInertiaProps` reads `User[]` back from it. A prop wrapped in `always()` is sent on every response, whatever the `only` and `except` lists say. The framework shares flashed validation errors this way, and a shared prop read from a flash needs the same treatment: the flash is consumed by the request whether or not the response carries it. ```typescript import { always, getSessionFromContext, shareInertiaProps } from '@guren/core' shareInertiaProps((ctx) => ({ flash: always(getSessionFromContext(ctx)?.getFlash('status')) }), container) ``` ## Deferred Props `defer()` keeps a prop out of the initial response and has the client fetch it right after the first render, so the page renders without waiting for a slow query: ```typescript import { Controller, defer } from '@guren/core' import { pages } from '@/.guren/pages.gen' export class UserController extends Controller { async index() { return this.inertia(pages.users.Index, { users: () => User.all(), permissions: defer(() => Permission.all()), teams: defer(() => Team.all(), 'attributes'), projects: defer(() => Project.all(), 'attributes'), }) } } ``` The initial page object lists the keys under `deferredProps`, grouped by the second argument (`default` when omitted): `{ "default": ["permissions"], "attributes": ["teams", "projects"] }`. The client issues one partial reload per group, so `teams` and `projects` arrive together while `permissions` loads in parallel. The callback runs only on that follow-up request. On the client the prop is `undefined` until its request lands, so declare it optional in `Props` and render it through ``, which shows the fallback until the value arrives. A required declaration still typechecks, since the controller may pass a deferred value for any prop; `guren check` warns when a controller passes `defer()` for a prop the page declares without `?`. ```tsx import type { PageProps } from '@guren/inertia-client/contracts' import { Deferred } from '@inertiajs/react' import { pages } from '@/.guren/pages.gen' type Props = PageProps export default function Index({ users, permissions }: Props) { return ( <> Loading permissions...

}>
) } ``` ## Assets and Styling The scaffold ships with Tailwind CSS preconfigured. Edit `resources/css/app.css` or add custom CSS frameworks as needed. If you introduce additional assets (images, fonts), place them under `public/`. Colors come from the Guren UI tokens in `resources/css/guren.css`: CSS variables such as `--g-accent` and `--g-text`, and Tailwind utilities over them such as `bg-g-panel`, `text-g-text-2` and `border-g-line`. The tokens switch with the system's dark mode, so a page styled with them needs no `dark:` variants. The scaffolded `.oxlintrc.json` enables `guren/no-raw-color` on `resources/js/`, which reports a palette class such as `bg-white` or `text-slate-500`, an arbitrary color such as `bg-[#db1b1b]`, and a hex value in a `style` prop. ## Favicon and Document Head The production document is built by the server, not from `public/index.html`, so a `` added to that file never reaches a browser. Register site-wide head markup with the `inertia` option instead. The scaffold already links the placeholder `public/favicon.svg` from `src/app.ts`: ```typescript const app = createApp({ inertia: { document: { head: '', }, }, // ... }) ``` The markup is emitted verbatim, so keep it to developer-authored strings. Files at the root of `public/` are served by the Bun runtime; on Node-based deployments serve them from a CDN. Files a browser would render as a *document* (`.html`, `.htm`, `.svg`, `.xhtml`, `.xml`) are served with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, so navigating straight to one downloads it instead of running its script on your origin. Images, scripts, stylesheets and fonts are unaffected: an ``, a CSS `url()` and a `` all still load, because the disposition only decides navigate-versus-download. An `