beromir / kirby-inertia
Inertia.js adapter for Kirby: explicit Inertia responses, with optional server-side rendering
Requires
- php: >=8.3
- getkirby/cms: ^6.0
- getkirby/composer-installer: ^1.2
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
An Inertia.js adapter for Kirby 6: templates and routes answer with explicit Inertia responses, with optional server-side rendering. Tested with Kirby 6.0, Inertia 3.7 and @inertiajs/svelte; the PHP side works with any Inertia client. MIT licensed; Kirby has its own license.
Install
composer require beromir/kirby-inertia
Composer installs the plugin to site/plugins/inertia. Load Kirby and Composer's autoloader, then create the plugin's application subclass, which adds $kirby->inertia():
// public/index.php require __DIR__ . '/../vendor/autoload.php'; echo (new Beromir\Inertia\App())->render();
Without Composer, copy this repository to site/plugins/inertia and require its bootstrap.php after Kirby's.
The subclass adds only inertia(); it does not replace routing, controllers, rendering, Panel, or API behavior. If you already extend Kirby's App, add the same convenience method to your class, or use Beromir\Inertia\Adapter::for($kirby) directly. The adapter is stored per application in a weak map; props are never kept in a process-wide shared bag.
The adapter resolves Vite's manifest relative to Kirby's index root. With a public/ document root, keep buildDirectory at assets/build and let Vite write to public/assets/build. Set Vite's publicDir: false so it does not copy the PHP document root into the build.
Templates and routes
// site/templates/article.php; Kirby controllers still run normally. $kirby->inertia()->share(['siteTitle' => $site->title()->value()]); echo $kirby->inertia()->render('Article', [ 'title' => $page->title()->value(), 'summary' => $summary, // explicitly selected controller output 'updatedAt' => fn () => gmdate('c'), ]);
Props must be null, scalars, arrays, or closures returning those values. Objects (including Kirby models and Fields) and resources are rejected. Convert models and fields explicitly. Closures can be nested inside arrays. Page props override shared props. errors is reserved for session validation messages; flash messages live in the Inertia 3 top-level flash object.
// A custom Kirby route's action: return $kirby->inertia()->response('Article', ['title' => 'Created'], 201);
Both methods share one response builder. render() returns the body and applies status, type and headers to Kirby's responder; response() returns a Kirby\Http\Response. The optional third argument sets HTTP status; otherwise the responder's existing status is preserved (default 200). Pass 404 explicitly in your error template, since Kirby may assign its fallback error status only after rendering.
Every adapter response disables Kirby's page cache and sends Cache-Control: no-store, private. Both HTML and JSON merge Vary: X-Inertia with existing values. Ordinary PHP templates, API routes, and Panel routes do not pass through the adapter. Clear old page cache entries once when adopting the adapter for an already-cached template.
Forms, redirects and sessions
// Prop for the form: 'csrf' => $kirby->csrf(), // Mutation route: validate explicitly before performing any action. $token = $kirby->request()->get('csrf'); if (!is_string($token) || !$kirby->csrf($token)) { return $kirby->inertia()->response('Error', [ 'status' => 403, 'title' => 'Session expired', 'message' => 'Refresh and retry.', ], 403); } return $kirby->inertia() ->errors(['email' => 'Enter a valid email.'], 'contact') ->redirect('/about'); // Successful submission: return $kirby->inertia()->flash(['success' => 'Done.'])->redirect('/about');
Use Inertia's errorBag: 'contact' option with a named bag. Omitting the bag argument uses X-Inertia-Error-Bag, or the default flat bag when absent. Empty errors serialize as {}. errors() and flash() replace their pending session values. Messages are consumed by the next successfully serialized adapter page response, including a partial reload, and remain untouched on redirects and asset-version mismatch responses. Non-adapter visits do not consume them. Prefetch requests (Purpose: prefetch) neither receive nor consume them, so they stay for the visit that is actually shown. Messages are session-scoped, not tab-scoped.
redirect($url, $status = null) defaults to 302 for GET/HEAD and 303 for mutation methods; explicit 302 after PUT/PATCH/DELETE becomes 303. location($url) sends an Inertia 409 with X-Inertia-Location, or an ordinary redirect for a normal browser request. Use trusted application destinations. Redirects are route responses; return them from the route action.
Assets and root HTML
Options in site/config/config.php:
return [ 'beromir.inertia.devServer' => getenv('VITE_DEV_SERVER') ?: null, 'beromir.inertia.entry' => 'frontend/app.ts', 'beromir.inertia.buildDirectory' => 'assets/build', 'beromir.inertia.root' => 'inertia/root', ];
devServer is explicit configuration; there is no automatic development-server probing. It loads Vite's client and the entry module. Production reads <index>/<buildDirectory>/.vite/manifest.json, follows static imports for CSS, and uses a SHA-256 hash of the manifest as the asset version. Missing manifests or entries fail clearly. Configure Vite's build directory, manifest, entry and base to match.
Override site/snippets/inertia/root.php or choose another snippet through root. It receives $pageJson (already safely JSON-encoded), $assets (whose tags() returns script/style tags), and $ssr (null or a validated renderer result). On SSR success, output implode("\n", $ssr['head']) inside the head and $ssr['body'] inside the body. The official renderer includes the page JSON and marked app container in its body; do not add them again. Render the generic fallback title only when $ssr is null. Existing custom snippets must adopt this branch to display SSR output.
When $ssr is null, keep:
<script data-page="app" type="application/json"><?= $pageJson ?></script> <div id="app"></div>
Do not HTML-entity encode $pageJson; script bodies are raw text. The adapter escapes slashes and HTML-significant characters to prevent hostile prop text from closing the script element. Use escaped attribute values for any extra markup you add.
Optional SSR
The independent plugin defaults to SSR disabled. Enable it explicitly:
'beromir.inertia.ssr.enabled' => true, 'beromir.inertia.ssr.url' => 'http://127.0.0.1:13714/render', 'beromir.inertia.ssr.timeout' => 2,
The URL is a full, trusted renderer endpoint; it must never come from request input. The transport uses Kirby's cURL-based HTTP client. The timeout is in whole seconds, minimum one. Map environment variables to these options in your config to switch SSR per environment.
Only full HTML responses invoke SSR, after props and closures have been resolved once. The renderer receives the same page object that will be hydrated. JSON/partial visits, redirects and asset-version conflicts bypass it. HTTP status and cache policy remain Kirby's responsibility. Messages are consumed once after either SSR HTML or the browser fallback is successfully constructed; version conflicts preserve them.
A successful response must contain a string body and a list of strings head. The root snippet trusts markup from this private service. Connection failures, timeouts, non-success statuses, malformed JSON and invalid shapes return the existing browser-rendered shell. PHP logs only component and failure category through error_log(). Fallback requires JavaScript and does not provide the page's SSR metadata.
Use the matching official @inertiajs/vite plugin with the shared Svelte entry point. Its development endpoint is /__inertia_ssr; the production server exposes /render and /health. The Svelte client hydrates the renderer's marked container automatically. Keep DOM-only code in browser lifecycle hooks and keep request data out of module-level application state. The PHP plugin remains frontend-agnostic and does not launch or supervise Node.
Supported scope
- Initial HTML and
X-Inertia: trueJSON responses, explicit props and HTTP status. - Shared props, lazy closure evaluation, top-level partial include/exclude filtering for a matching component. Exclusion wins over inclusion;
errorsis always present. - GET asset-version mismatch: 409, relative URL (including query), current version header, no
X-Inertiapage header. Pending session messages survive the resulting document reload. - Mutation redirects, external locations, named validation errors, Inertia 3 flash data.
- Link prefetching: prefetch responses leave session messages in place.
- Svelte persistent layouts, hydration and history through the official client.
- Optional initial-page SSR through an HTTP renderer, with browser fallback.
Not implemented: deferred/merge/once props, dotted/nested partial selectors, infinite-scroll protocol, fragment-specific redirect controls, precognition, history encryption controls, authentication UI, or multilingual-specific integration. This is a tested subset, not a claim of complete Inertia 3 server-adapter parity. Responses assume a conventional Kirby request lifecycle, one application instance per HTTP request.
Tests
KIRBY_BOOTSTRAP=/absolute/path/kirby/bootstrap.php php tests/run.php (or composer test with the variable set). The PHP suite requires CLI process creation for a temporary renderer fixture. Tests create and remove an isolated temporary site; no live content or sessions are changed.
The implementation follows the Inertia 3 protocol, with the limitations above.
Releasing
Packagist picks up tags through its GitHub hook. Tag releases v0.2.0 and push them with git push --follow-tags.