Search by

wielorzeczownik / phalcon-inertia

wielorzeczownik

Inertia.js server adapter for Phalcon 3.4 to 6, with Ziggy style named routes for JavaScript.

Package info

github.com/wielorzeczownik/phalcon-inertia

Homepage

pkg:composer/wielorzeczownik/phalcon-inertia

Statistics

Installs: 124

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 2

v1.4.0 2026-11-30 21:31 UTC

This package is auto-updated.

Last update: 2026-12-04 18:43:43 UTC


README

phalcon-inertia logo

Phalcon Inertia

Release Packagist Packagist downloads License: MIT
PHP Phalcon Inertia.js TypeScript Vite

Inertia.js for Phalcon. Your controllers stay on the Phalcon router and return Vue, React or Svelte pages instead of views, so you don't need a separate API in between.

It also comes with route(), a port of Ziggy, so you can use your named Phalcon routes in JavaScript.

Phalcon Installed as PHP
3.4, 4, 5 the C extension (ext-phalcon) 5.6 - 8.5
6 the phalcon/phalcon Composer package 8.1+

On the frontend you need the Inertia v3 client for Vue, React or Svelte.

Protocol coverage. Supported: optional, deferred and rescued deferred props, always props, merge and deep merge, once props, infinite scroll, live props, external redirects, flash data, history encryption, big integers, Precognition, SSR, DevTools and testing helpers.

Installation

composer require wielorzeczownik/phalcon-inertia
npm install vite laravel-vite-plugin

Then install the Inertia client for your framework (@inertiajs/vue3, /react or /svelte, version 3.x) and its Vite plugin. Older clients won't start: they look for the first page in a data-page attribute, while v3 puts it in a <script type="application/json"> element.

laravel-vite-plugin works fine without Laravel. The Vite helper reads the public/hot file it writes in development and the public/build directory it builds to.

route() ships prebuilt inside the Composer package, so there's nothing to install from npm. Point an alias at it, the same way Ziggy is set up from vendor/tightenco/ziggy:

// vite.config.js
import path from 'node:path';
import laravel from 'laravel-vite-plugin';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    laravel({ input: ['resources/js/app.js'], ssr: 'resources/js/ssr.js' }),
    // your framework plugin, e.g. vue(), react() or svelte()
  ],
  resolve: {
    alias: {
      'phalcon-routes': path.resolve(
        'vendor/wielorzeczownik/phalcon-inertia/js'
      ),
    },
  },
});

Then create resources/js/app.js as in the Inertia client-side setup and add route() for your framework. Complete Vue, React and Svelte examples with SSR are in the e2e app.

Setup

Register the service provider and give the application the same events manager:

use PhalconInertia\InertiaServiceProvider;

$di->register(new InertiaServiceProvider([
    'rootView' => APP_PATH.'/views/app.php',
    'publicPath' => BASE_PATH.'/public',
]));

$application->setEventsManager($di->getShared('eventsManager'));

It sets up the inertia, vite, routes and csrf services and hooks its listeners into the eventsManager service and the dispatcher. It implements Phalcon\Di\ServiceProviderInterface on every supported version, from 3.4 to 6. All options are under Configuration.

Registering the services by hand
use Phalcon\Events\Manager;
use PhalconInertia\Csrf;
use PhalconInertia\Inertia;
use PhalconInertia\Routes;
use PhalconInertia\Vite;

$di->setShared('vite', function () {
    return new Vite(BASE_PATH.'/public');
});
$di->setShared('routes', Routes::class);
$di->setShared('csrf', Csrf::class);
$di->setShared('inertia', function () use ($di) {
    return new Inertia(APP_PATH.'/views/app.php', $di->getShared('vite')->version());
});

$events = new Manager;
$events->attach('application:beforeSendResponse', $di->getShared('inertia'));
$events->attach('dispatch:beforeException', $di->getShared('inertia'));
$events->attach('dispatch:beforeExecuteRoute', $di->getShared('csrf'));

$di->getShared('dispatcher')->setEventsManager($events);
$application->setEventsManager($events);

The constructor arguments are listed under Class settings.

Root view

The root view is a plain PHP file. It runs inside the Inertia service, so $this gives you the DI, and it gets three variables:

  • $page, the page array,
  • $head, head tags from SSR (empty without SSR),
  • $body, the mount point with the page data, or the SSR markup.
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <?= $this->routes->script() ?>
    <?= $this->vite->tags('resources/js/app.js') ?>
    <?= $head ?>
</head>
<body>
    <?= $body ?>
</body>
</html>

$this->routes->script() prints the route config and the route() function, much like @routes in Laravel.

To write it in Volt (or any engine registered on your view service), pass a view name instead of a file path. It's rendered with $this->view->getPartial(), so view variables, partials and your own Volt functions all work, and page, head and body are added to the view variables:

'rootView' => 'app', // views/app.volt
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    {{ routes.script() }}
    {{ vite.tags('resources/js/app.js') }}
    {{ head }}
</head>
<body>
    {{ body }}
</body>
</html>

To use a different root view for one request:

return $this->inertia->setRootView(APP_PATH.'/views/admin.php')->render('Admin/Index');

Vite and asset versioning

$this->vite->tags($entries, $nonce) prints the dev server client and your entries while public/hot exists. Otherwise it prints the built script, its CSS and modulepreload links from the manifest. asset($path) returns the URL of any built file.

Vite::version() returns a hash of the build manifest, which the provider uses as the asset version. If an Inertia GET comes in with a different version, the response is 409 Conflict with X-Inertia-Location and the client does a full reload. Errors and flash data in the session survive it.

Pages and props

class UsersController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        return $this->inertia->render('Users/Index', [
            'users' => Users::find()->toArray(),
        ]);
    }
}
  • Closures run only when their prop is actually sent. A partial reload that skips a prop skips its query too.
  • inertia('Users/Index', $props) is a global shortcut for render(), and inertia() with no arguments returns the service.
  • Integers beyond JavaScript's safe range, like BIGINT ids, lose precision in JSON.parse. $this->inertia->preserveBigIntegers() sends them as {"$bigint": "..."} in props and flash data, and the client turns them into BigInt.

$this->inertia comes from the DI container, so your IDE doesn't know its type. Declare it on a base controller:

/**
 * @property \PhalconInertia\Inertia $inertia
 */
class ControllerBase extends \Phalcon\Mvc\Controller
{
}

Shared props

$this->inertia->share('auth', function () {
    return ['user' => $this->session->get('user')];
});

Shared props go to every page and are listed in sharedProps. A prop passed to render() with the same key wins.

Prop types

use PhalconInertia\Inertia;

return $this->inertia->render('Dashboard', [
    'stats' => Inertia::defer(function () { return Stats::heavy(); }),
    'sidebar' => Inertia::defer(function () { return Menu::all(); }, 'aside'),
    'audit' => Inertia::optional(function () { return Audit::recent(); }),
    'flags' => Inertia::always(Features::all()),
    'posts' => Inertia::merge($page->items)->matchOn('id'),
    'feed' => Inertia::merge($items)->prepend(),
    'settings' => Inertia::deepMerge($settings),
    'plans' => Inertia::once(function () { return Plan::all(); }),
    'permissions' => Inertia::defer(function () { return Acl::load(); }, 'default', true),
    'timeline' => Inertia::scroll($paginator->paginate()),
]);
Factory Sent on the first visit Sent on a partial reload
plain value or closure yes when requested
Inertia::always($value) yes always, even when not listed
Inertia::optional($callback) no when requested
Inertia::defer($callback, $group) no, fetched right after when requested
Inertia::merge($value) yes when requested, merged by the client
Inertia::deepMerge($value) yes when requested, deep merged
Inertia::once($callback) yes, unless the client has it when requested
Inertia::scroll($page) yes when requested, merged by the client
Inertia::live($value, $on, $chan) yes when requested or broadcast

append(), prepend(), deep() and matchOn($field) chain onto Inertia::defer() too, defer($group) chains onto Inertia::scroll() and Inertia::merge(), and live($on, $channel) chains onto everything except merge and scroll props. Every factory also exists on PhalconInertia\Prop, except once(), which there is Prop::value($value)->once().

Nested props

Prop types work at any depth, and partial reloads take dot paths. A key with a dot goes into the prop it points into:

return $this->inertia->render('Users/Show', [
    'user' => ['name' => $user->name],
    'user.permissions' => Inertia::defer(function () use ($user) { return $user->permissions(); }),
]);

The first visit sends user.name and lists user.permissions under deferredProps. <Deferred data="user.permissions"> then loads it, and router.reload({ only: ['user.permissions'] }) reloads only that.

Children of a closure or a prop type are sent whole once their parent is selected, so only: ['team.name'] on a 'team' => function () {...} prop returns all of team.

Rescued deferred props

Pass true as the third argument of defer() and an exception from its callback won't fail the page. It goes to the logger service (or error_log() if there isn't one), the prop is dropped and listed in rescuedProps, and the rest of the page loads normally. <Deferred> then renders its rescue slot, and router.reload({ only: ['permissions'] }) retries.

Once props

A once prop is resolved on the first visit and then kept by the client. On later visits the client lists the props it already has in X-Inertia-Except-Once-Props, and their callbacks don't run.

Inertia::once($callback)->until(3600); // seconds, a DateTimeInterface or a DateInterval
Inertia::once($callback)->fresh(); // resolve it again on this response
Inertia::once($callback)->key('billing'); // Laravel's as(), a reserved word on PHP 5.6
Inertia::defer($callback)->once(); // once chains onto other props too

The client only keeps props of the current page. To keep one across pages, share it with shareOnce('plans', $callback). It returns the prop, so until(), key() and fresh() chain onto it.

Infinite scroll

Inertia::scroll() takes a page from a Phalcon paginator (any supported version) and gives <InfiniteScroll> the items under data plus the current, previous and next page numbers. The client asks for pages through the page query parameter, so pass it on to the paginator:

use Phalcon\Paginator\Adapter\NativeArray;

$paginator = new NativeArray([
    'data' => $posts,
    'limit' => 20,
    'page' => max(1, (int) $this->request->getQuery('page', 'int', 1)),
]);

return $this->inertia->render('Posts/Index', [
    'posts' => Inertia::scroll($paginator->paginate()),
]);
<InfiniteScroll data="posts">
  <article v-for="post in posts.data" :key="post.id">{{ post.title }}</article>
</InfiniteScroll>

For data that doesn't come from a Phalcon paginator, pass the wrapper key and the metadata yourself, e.g. Inertia::scroll(['items' => $items], 'items', ['currentPage' => 2, 'previousPage' => 1, 'nextPage' => 3]). The metadata can also be a PhalconInertia\ProvidesScrollMetadata object, or a callable that gets the value and returns either.

Inertia::scroll($page)->defer() loads the first page right after the page renders, like Inertia::defer(), and takes the group as its argument. Whether new items are appended or prepended follows the client's X-Inertia-Infinite-Scroll-Merge-Intent header.

Live props

A live prop reloads itself when one of its events is broadcast. The page lists its channels and events under liveProps, the client subscribes and runs router.reload({ only: [...] }) when one arrives, at most once per $throttle milliseconds (1000 by default).

use PhalconInertia\Channel;

return $this->inertia->render('Orders/Index', [
    'orders' => Inertia::live(function () { return Order::recent(); }, 'OrderShipped', 'orders'),
    'inbox' => Inertia::defer(function () use ($user) { return $user->messages(); })
        ->live(['MessageSent', 'MessageRead'], new Channel('user.'.$user->id, 'private'), 500),
]);

A string channel is public. new Channel($name, $type) takes private, presence or encrypted-private, with the name unprefixed: the client's transport adds private- and the like. Chain live() again for events on other channels.

The adapter only describes what to listen for. Sending events stays with the app, e.g. with pusher/pusher-php-server against Pusher, Soketi or Reverb. Pass socketId() so the browser that made the change isn't sent its own event:

$pusher->trigger('orders', 'OrderShipped', ['id' => $order->id], ['socket_id' => $this->inertia->socketId()]);

On the client, hand the transport to createInertiaApp(). Private and presence channels authorize through the Pusher client's own channelAuthorization endpoint, which the app provides.

import Pusher from 'pusher-js';
import { pusher } from '@inertiajs/core/pusher';

createInertiaApp({
  live: pusher({
    client: new Pusher(import.meta.env.VITE_PUSHER_KEY, { cluster: 'eu' }),
  }),
  // ...
});

Props from objects

An object can shape its own prop. ProvidesInertiaProperty turns an object used as a prop value into that value, and ProvidesInertiaProperties lets an object passed without a key to render() or share() provide several props at once.

Example
use PhalconInertia\PropertyContext;
use PhalconInertia\ProvidesInertiaProperties;
use PhalconInertia\ProvidesInertiaProperty;
use PhalconInertia\RenderContext;

class UserResource implements ProvidesInertiaProperty
{
    public function toInertiaProperty(PropertyContext $prop)
    {
        return ['id' => $this->user->id, 'name' => $this->user->name];
    }
}

class CurrentUserProps implements ProvidesInertiaProperties
{
    public function toInertiaProperties(RenderContext $context)
    {
        return ['user' => ..., 'permissions' => ...];
    }
}

$this->inertia->share([new CurrentUserProps($auth)]);
return $this->inertia->render('Users/Show', ['user' => new UserResource($user)]);

PropertyContext has the prop's dot path ($prop->key), the props on the same level ($prop->props) and the request ($prop->request). RenderContext has the component name ($context->component) and the request. Page props still win over shared ones with the same name.

Forms and validation

Reading input

The v3 client sends JSON, which $request->getPost() can't read on Phalcon 3.4. input() reads JSON, form and PUT bodies on every version. It takes the same arguments as getPost(): name, filters, default and notAllowEmpty.

$name = $this->inertia->input('name', 'trim');
$page = $this->inertia->input('page', 'int', 1);
$all = $this->inertia->input();

Filters are Phalcon's own and behave as in getPost(). On 3.4, for example, int returns '5', while 4 and 5 return 5.

Validation

validate() is Laravel's $request->validate(). It validates the input and returns it. If validation fails, it saves the errors and throws a ValidationException, which the dispatch:beforeException listener turns into a redirect back.

public function storeAction()
{
    $data = $this->inertia->validate($validation);
    Users::create($data);

    return $this->response->redirect('users');
}

The second argument is other data to validate, the third an error bag name (like validateWithBag()). To handle errors yourself, use withErrors() and back():

$messages = $validation->validate($this->inertia->input());
if (count($messages)) {
    $this->inertia->withErrors($messages);

    return $this->inertia->back();
}
  • withErrors() accepts Phalcon validation messages or a field => message array and keeps the first message for each field. Its second argument picks a named bag, and the X-Inertia-Error-Bag header from useForm({ errorBag }) is respected.
  • The next page gets them in the errors prop, which is always there ({} when empty).
  • back($fallback = '/') follows the referrer only if it's on the same host, so a forged Referer can't send users off-site.

Precognition

validate() handles Precognition requests too, so forms can show server side errors while the user types, without copying any rules to JavaScript. The controller stays the same:

const form = useForm('post', route('users.store'), { name: '' });
<input v-model="form.name" @change="form.validate('name')" />
<p v-if="form.errors.name">{{ form.errors.name }}</p>
<button @click="form.submit()">Create</button>

With the Precognition header, the response only reports errors for the fields in Precognition-Validate-Only, nothing goes into the session, and the action stops with 204 (valid) or 422 with the errors.

Warning

A Precognition request runs the action up to the validate() call. Put the call before anything with side effects.

CSRF

Csrf keeps a token in the session, sends it as the XSRF-TOKEN cookie and checks it on every request except GET, HEAD and OPTIONS. The Inertia client sends it back in X-XSRF-TOKEN on its own, and X-CSRF-TOKEN or a _token form field work too. A missing or wrong token stops the request before the controller with 419 Page Expired.

The check covers the whole application, so plain HTML forms need a _token field filled with $this->csrf->token(). The cookie is SameSite=Lax, and Secure over HTTPS.

Regenerate the token along with the session ID when a user logs in or out:

$this->session->regenerateId();
$this->csrf->regenerate();

Actions that change data must not answer GET, HEAD or OPTIONS, because those are never checked. Register them with addPost(), addPut(), addPatch() or addDelete(), not add(), which accepts any method.

Responses

Flash data, redirects and history

$this->inertia->flash('status', 'Saved');
$this->inertia->clearHistory();
return $this->response->redirect('users');

return $this->inertia->location('https://payments.example.com/checkout');
  • Flash data shows up on the next page as usePage().flash.
  • After PUT, PATCH or DELETE, a redirect becomes 303 See Other.
  • A redirect to a URL with a fragment, like redirect('posts#comments'), becomes 409 with X-Inertia-Redirect. The client follows it and keeps the fragment.
  • preserveFragment() keeps the fragment of the visited URL after the next redirect, even when the redirect goes somewhere else.
  • An action that returns nothing to an Inertia request redirects back.
  • location() leaves the app with a full page load.
  • encryptHistory() on the service turns on history encryption for every page.

Error pages

$router->notFound(['controller' => 'errors', 'action' => 'notFound']);

public function notFoundAction()
{
    return $this->inertia->render('Error', ['status' => 404])->setStatusCode(404, 'Not Found');
}

Handle exceptions the same way in a dispatch:beforeException listener. Otherwise the client shows the raw error response in a modal.

The library's own errors are thrown as PhalconInertia\Exception, e.g. when the Vite manifest or the session service is missing. It extends \Exception, and ValidationException extends it.

Server side rendering

use PhalconInertia\SsrGateway;

$di->getShared('inertia')->setSsr(new SsrGateway('http://127.0.0.1:13714', 2));

With the provider, the ssr option does the same. Build with vite build && vite build --ssr, then keep node bootstrap/ssr/ssr.js running under systemd, supervisor or pm2.

The first visit goes to that server, and what it returns ends up in $head and $body. If the server is down, slow or fails, the page falls back to client rendering. Inertia visits never hit it. For route() during SSR, see Under SSR.

DevTools

The Inertia DevTools extension shows each request's page, props and headers. Turn recording on in development only, since entries hold request and page data:

$di->register(new InertiaServiceProvider([
    // ...
    'devtools' => getenv('APP_ENV') === 'development',
]));

Every response then carries X-Inertia-Devtools-Id, and the adapter adds GET /_inertia/devtools/entries/{id} to the router, where the extension reads the entry. Entries are kept in the session, the newest 20 per browser tab, so a browser only ever sees its own. Keys that look like passwords, tokens, secrets or cookies are redacted.

Without the provider, call $inertia->devtools(), attach the Inertia listener to application:beforeSendResponse and add the route with PhalconInertia\Devtools::route($router).

Routes in JavaScript

route() takes a route name and its parameters and returns the URL, with the same API as Ziggy. Only named routes are exported. With script() in the root view, route() works everywhere in the browser.

If you know Ziggy, this is how the names map:

Ziggy phalcon-inertia
@routes <?= $this->routes->script() ?>, in Volt {{ routes.script() }}
@routes('author') <?= $this->routes->script('author') ?>, in Volt {{ routes.script('author') }}
(new Ziggy)->toArray() $this->routes->toArray()
php artisan ziggy:generate --types $this->routes->types()
ziggy-js phalcon-routes
ZiggyVue RouteVue
useRoute() useRoute()
config/ziggy.php routes option, or a Phalcon\Config
URL::defaults() defaults in the routes option

Parameters

$router->addGet('/posts', 'Posts::index')->setName('posts.index');
$router->addGet('/posts/{post}', 'Posts::show')->setName('posts.show');
$router->addGet('/venues/{venue}/events/{event}', 'Events::show')->setName('venues.events.show');
route('posts.index'); // 'https://example.com/posts'

route('posts.show', 1); // 'https://example.com/posts/1'
route('posts.show', [1]); // same
route('posts.show', { post: 1 }); // same

route('venues.events.show', [1, 2]); // 'https://example.com/venues/1/events/2'
route('venues.events.show', { venue: 1, event: 2 }); // same

Arguments that match no route parameter become query parameters. A query parameter with the same name as a route parameter goes under _query:

route('venues.events.show', { venue: 1, event: 2, page: 5 });
// 'https://example.com/venues/1/events/2?page=5'

route('venues.events.show', {
  venue: 1,
  event: 2,
  _query: { event: 3, page: 5 },
});
// 'https://example.com/venues/1/events/2?event=3&page=5'

route('posts.index', {
  _query: { draft: false, tags: ['php', 'vue'], author: null },
});
// 'https://example.com/posts?draft=0&tags[0]=php&tags[1]=vue'

Booleans become 1 and 0, null values are dropped, and arrays and objects use PHP-style brackets.

URLs are absolute by default. Pass false as the third argument to get a path. The Phalcon base URI stays in it:

route('posts.show', 1, false); // '/posts/1', or '/app/posts/1' with the base URI '/app/'

Default values

Values every URL shares, like a locale, can be set once under defaults in the route options. This replaces Laravel's URL::defaults():

$router->addGet('/{locale}/posts/{post}', 'Posts::show')->setName('posts.show');

$di->register(new InertiaServiceProvider([
    // ...
    'routes' => ['defaults' => ['locale' => 'en']],
]));
route('posts.show', 1); // 'https://example.com/en/posts/1'
route('posts.show', { locale: 'pl', post: 1 }); // 'https://example.com/pl/posts/1'

Constraints

Constraints from the Phalcon route carry over, and route() throws when a value wouldn't match:

$router->addGet('/users/{id:[0-9]+}', 'Users::show')->setName('users.show');
$router->addGet('/legacy/:int', ['controller' => 'legacy', 'id' => 1])->setName('legacy.show');
route('users.show', 5); // 'https://example.com/users/5'
route('users.show', 'ada');
// Error: Route error: 'id' parameter does not match required format '[0-9]+' for route 'users.show'.

A constraint that allows slashes, like {path:.+}, keeps them in the URL.

Objects as parameters

Phalcon has no route-model binding. An object passed as a parameter resolves to its id, which covers toArray() models and most API payloads:

const post = { id: 3, title: 'Hello', slug: 'hello' };

route('posts.show', post); // 'https://example.com/posts/3'
route('posts.comments.show', [post, { id: 7 }]); // 'https://example.com/posts/3/comments/7'
route('posts.show', post.slug); // any other key, pass it yourself

Current route

Called with no arguments, route() returns a Router:

// at https://example.com/posts/4?lang=en, with 'posts.show' at '/posts/{post}'

route().current(); // 'posts.show'
route().current('posts.index'); // false
route().current('posts.*'); // true
route().current('posts.show', { post: 4 }); // true
route().current('posts.show', { post: 1 }); // false

route().has('posts.show'); // true
route().has('payments.index'); // false

route().params; // { post: '4', lang: 'en' }

Values in params are always strings, because they come from the URL.

If two routes match the URL, the one added last wins, as in the Phalcon router. Constraints like {post:[0-9]+} keep /posts/create and /posts/{post} apart.

Examples

import { router, useForm } from '@inertiajs/vue3';

const form = useForm({ title: '' });
form.post(route('posts.store'));

router.delete(route('posts.destroy', post));

const response = await fetch(route('posts.index', { _query: { page: 2 } }));

Where Phalcon differs from Laravel

  • Constraints like {id:[0-9]+} or :int become wheres. route() rejects values that wouldn't match, and current() can tell /users/create from /users/{id}.
  • current() checks routes from last added to first, the same order the Phalcon router uses.
  • The base URI stays in relative URLs (/app/users/5). Plain hostnames from setHostname() become the route domain, regex hostnames are skipped.
  • There's no route-model binding or route middleware. Objects resolve to their id, and URL defaults come from defaults in the route options.

Frameworks, SSR and TypeScript

For most apps, script() in the root view is all you need. It prints the route config and inlines route(), which then works in any script, with or without a bundler. The helpers below pick it up on their own.

Vue

RouteVue adds route() to templates and to inject('route'):

import { createApp } from 'vue';
import { RouteVue } from 'phalcon-routes';
import App from './App.vue';

createApp(App).use(RouteVue);
<script setup>
import { Link } from '@inertiajs/vue3';
import { inject } from 'vue';

defineProps({ post: Object });

const route = inject('route');
</script>

<template>
  <Link :href="route('posts.show', post)">{{ post.title }}</Link>
</template>

React

import { Link } from '@inertiajs/react';
import { useRoute } from 'phalcon-routes';

export default function Post({ post }) {
  const route = useRoute();

  return <Link href={route('posts.show', post)}>{post.title}</Link>;
}

Svelte

<script>
  import { Link } from '@inertiajs/svelte';
  import { useRoute } from 'phalcon-routes';

  let { post } = $props();

  const route = useRoute();
</script>

<Link href={route('posts.show', post)}>{post.title}</Link>

Bundling the config

To bundle the config instead of printing it in the page, write it to a file at build time:

file_put_contents(BASE_PATH.'/resources/js/routes.json', $di->getShared('routes')->toJson());
import { route, RouteVue, useRoute } from 'phalcon-routes';
import routes from './routes.json';

route('posts.show', post, undefined, routes);
createApp(App).use(RouteVue, routes); // Vue
const route = useRoute(routes); // React, Svelte

You then don't need the inlined route() from script(). Pass false as its fourth argument to print only the config, or drop script() altogether.

Separate frontends

A frontend that Phalcon doesn't render, or that lives in another repository, has no vendor/ to alias. Copy js/dist from the Composer package into it (plain ES modules with types), and serve the config from an endpoint:

public function routesAction()
{
    return $this->response
        ->setContentType('application/json', 'UTF-8')
        ->setContent($this->routes->toJson(['api.*']));
}
const config = await fetch('/routes').then((response) => response.json());
const route = useRoute(config);

Under SSR

The SSR server is a separate Node process. It has no window and never sees the script() output, so give it the route config as a shared prop:

$di->getShared('inertia')->share('routes', function () use ($di) {
    return $di->getShared('routes')->toArray();
});

In the SSR entry, pass it on together with a location, which current() and params need. With Vue, the client entry keeps .use(RouteVue):

// resources/js/ssr.js
setup({ App, props, plugin }) {
  const routes = props.initialPage.props.routes;

  return createSSRApp({ render: () => h(App, props) })
    .use(plugin)
    .use(RouteVue, { ...routes, location: new URL(props.initialPage.url, routes.url) });
},

For React and Svelte, pass the same object to useRoute() in the SSR render, e.g. from usePage() as the e2e app does for React and Svelte.

TypeScript

types() generates a declaration of every route and its parameters (Ziggy's ziggy:generate --types). Save it with your sources to get autocompletion and type checks for route names and parameters:

file_put_contents(BASE_PATH.'/resources/js/routes.d.ts', $di->getShared('routes')->types());

types() reads the router, so it has to run where your routes are registered. A CLI task called from your deploy script works well. The CLI application needs the same router and url services as the web one:

class RoutesTask extends \Phalcon\Cli\Task
{
    public function typesAction()
    {
        file_put_contents(BASE_PATH.'/resources/js/routes.d.ts', $this->routes->types());
    }
}

Types for route() itself ship with the package. Map the alias in tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "phalcon-routes": ["./vendor/wielorzeczownik/phalcon-inertia/js"]
    }
  }
}

Then declare the global route() from script(), and for Vue the one in templates:

import type { route as routeFn } from 'phalcon-routes';

declare global {
  var route: typeof routeFn;
}

declare module 'vue' {
  interface ComponentCustomProperties {
    route: typeof routeFn;
  }
}

Filtering routes

Without filters, every named route ends up in the browser, admin ones too.

Important

Filtering hides route names from the page, it doesn't protect them. Every endpoint still needs its own authorization.

Set only or except in the route options, with * as a wildcard. They apply to every call of script(), toArray() and types():

$di->register(new InertiaServiceProvider([
    // ...
    'routes' => [
        'except' => ['admin.*', 'debug.*'],
    ],
]));

The options can come from your Phalcon config as well, as an array or a Phalcon\Config:

// app/config/config.php
'routes' => [
    'only' => ['posts.*', 'home'],
],

// services
'routes' => $di->getShared('config')->routes,

A route is exported if it matches only (or only is empty) and doesn't match except. Patterns passed to a call override the options, and an empty array turns a filter off:

$this->routes->toArray(['posts.*'], ['posts.drafts.*']);
$this->routes->toArray([], []); // every named route

Groups

Named sets of patterns go under groups. A group name works anywhere a pattern does:

'routes' => [
    'groups' => [
        'admin' => ['admin.*', 'users.*'],
        'author' => ['posts.*'],
    ],
],
<?= $this->routes->script('author') ?>
<?= $this->routes->script(['admin', 'author']) ?>
<?= $this->routes->script([], 'admin') ?>

If a group and a route share a name, the group wins, so don't name a group after a route.

script() arguments

script($only, $except, $nonce, $withFunction). The third argument is a nonce for a Content Security Policy, as with $this->vite->tags(). The fourth, when false, prints only the config without the inlined route():

<?= $this->routes->script([], [], $cspNonce) ?>
<?= $this->routes->script([], [], null, false) ?>

Testing

Add the InteractsWithInertia trait to a PHPUnit test case. It works with both JSON and HTML responses.

use PhalconInertia\Testing\InteractsWithInertia;

class UsersTest extends \PHPUnit\Framework\TestCase
{
    use InteractsWithInertia;

    public function test_index()
    {
        $this->assertInertia($response, function ($page) {
            $page->component('Users/Index')
                ->has('users', 3)
                ->where('users.0.name', 'Ada')
                ->missing('users.0.password');
        });
    }
}

component(), url(), version(), has($key, $count), where($key, $valueOrCallback) and missing($key) take dot paths into the props. prop($key) returns the raw value for your own assertions.

A callback scopes into a prop. has('users.0', $callback) scopes into that object, and has('users', 3, $callback) checks the count first and then scopes into the first item. Inside a scope every prop has to be asserted, or the test fails. Call etc() to allow the rest:

$page->has('users', 3, function ($user) {
    $user->where('id', 1)
        ->where('name', 'Ada')
        ->missing('password')
        ->etc();
});

Configuration

InertiaServiceProvider options:

Option Required Default Meaning
rootView yes - path to the root view PHP file, or a view name
publicPath yes - public directory with hot and the build directory
version no hash of the Vite manifest asset version, compared with X-Inertia-Version
buildDirectory no build build directory inside the public directory
assetUrl no / base URL for built files, e.g. a CDN
routes no [] route options
csrf no true attaches the Csrf listener
ssr no off URL of the SSR server, e.g. http://127.0.0.1:13714
ssrTimeout no 2 seconds to wait before falling back to client rendering
devtools no false records requests for DevTools

Route options

The provider's routes option and the Routes constructor take the same keys:

Key Default Meaning
url scheme, host and base URI of a request base URL of absolute routes
only [] patterns or group names of routes to export, empty for all
except [] patterns or group names of routes to leave out
groups [] named sets of patterns, usable wherever a pattern goes
defaults [] default parameter values for route()

Behind a proxy that terminates TLS, Phalcon may see http and build http URLs. Set url to your public address then, e.g. 'routes' => ['url' => 'https://example.com'].

Class settings

For setups without the provider:

Setting Required Default Meaning
Inertia $rootView yes - path to the root view PHP file, or a view name
Inertia $version no '' asset version, compared with X-Inertia-Version
Inertia::setRootView() no the constructor value root view for the current request
Inertia::encryptHistory() no off sets encryptHistory on every page
Inertia::preserveBigIntegers() no off sends integers beyond JavaScript's safe range as BigInt
Inertia::setSsr() no off SsrGateway used for the first visit
Inertia::devtools($limit) no off records requests for DevTools, $limit entries per tab
SsrGateway $url no http://127.0.0.1:13714 base URL of the SSR server, /render is appended
SsrGateway $timeout no 2 seconds to wait before falling back to client rendering
Vite $publicPath yes - public directory with hot and the build directory
Vite $buildDirectory no build build directory inside the public directory
Vite $assetUrl no / base URL for built files, e.g. a CDN
Routes $options no [] route options, as an array or a Phalcon\Config
session service no - needed by withErrors(), flash(), clearHistory(), preserveFragment() and Csrf
logger service no - gets rescued deferred props through error(), else error_log()
allow_url_fopen no PHP default needed by SsrGateway

Credits

route() follows the API of Ziggy by Tighten. Where the Inertia protocol leaves room for choices, the server side follows the official Laravel adapter.

Disclaimer

Not official and not affiliated with Phalcon, Inertia.js or Laravel. If the Inertia protocol changes, this may break until it's fixed here.