inventor96/inertia-mako

The Mako adapter for Inertia.js.

v1.3.0 2025-08-19 09:36 UTC

This package is auto-updated.

Last update: 2025-08-19 23:38:49 UTC


README

An Inertia.js server-side adapter for the PHP Mako framework.

The examples below are for Vue.js.

Installation

  1. Install the composer and npm packages:

    composer create-project mako/app <project-name> # from mako's documentation
    cd <project-name>
    composer require inventor96/inertia-mako
    npm install @inertiajs/inertia @inertiajs/vue3 @vitejs/plugin-vue laravel-vite-plugin vite vue --save-dev

    Yes, the laravel vite plugin is intentional. We could create our own, but that would pretty much be reinventing the wheel, or just changing the name while the underlying code is untouched. Note that when running npm run dev later, the Laravel plugin will report the APP_URL as undefined, but that's OK for our situation.

  2. Set other npm configs:
    package.json

    {
        "private": true,
        "type": "module",
        "scripts": {
            "dev": "vite",
            "build": "vite build",
            "serve": "vite preview"
        },
        ...
    }
  3. Create the vite config:
    vite.config.js

    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    import vue from '@vitejs/plugin-vue';
    import path from 'path';
    
    export default defineConfig({
        plugins: [
            laravel({
                input: 'app/resources/js/app.js',
                refresh: true,
            }),
            vue({
                template: {
                    transformAssetUrls: {
                        base: null,
                        includeAbsolute: false,
                    },
                },
            }),
        ],
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'app/resources/views'),
            },
        },
        build: {
            outDir: 'public/build',
            assetsDir: 'assets',
        },
    });
  4. Create the JS app file:
    app/resources/js/app.js

    import { createApp, h } from 'vue'
    import { createInertiaApp } from '@inertiajs/vue3'
    // import Default from '@/Layouts/Default.vue' // uncomment if you want to use a default layout
    
    createInertiaApp({
        resolve: (name) => {
            const pages = import.meta.glob('../views/Pages/**/*.vue', { eager: true });
            let page = pages[`../views/Pages/${name}.vue`];
            // uncomment if you want to use a default layout
            /* if (page.default.layout === undefined) {
                page.default.layout = Default;
            } */
            return page;
        },
        setup({ el, App, props, plugin }) {
            createApp({ render: () => h(App, props) })
                .use(plugin)
                .mount(el);
        },
    });
  5. Enable the package in Mako:
    app/config/application.php

    [
        'packages' => [
            'web' => [
                inventor96\Inertia\InertiaPackage::class,
            ],
        ],
    ];
  6. Register the middlewares:
    app/http/routing/middleware.php

    $dispatcher->registerGlobalMiddleware(inventor96\Inertia\InertiaCsrf::class);
    $dispatcher->registerGlobalMiddleware(inventor96\Inertia\InertiaInputValidation::class);
    $dispatcher->registerGlobalMiddleware(inventor96\Inertia\InertiaMiddleware::class);
    
    // optionally, define the middleware order. e.g.:
    $dispatcher->setMiddlewarePriority(inventor96\Inertia\InertiaCsrf::class, 50);
    $dispatcher->setMiddlewarePriority(inventor96\Inertia\InertiaInputValidation::class, 60);
    $dispatcher->setMiddlewarePriority(inventor96\Inertia\InertiaMiddleware::class, 70);

Configuration

If you would like to override the default configuration, create a new file at app/config/packages/inertia/inertia.php.

The following configuration items and their defaults are as follows:

<?php
return [
    /**
     * The view to use when rendering the full HTML page for the
     * initial response to the browser. This config is relative
     * to the `app/resources/views` directory.
     * e.g. `'app'` would resolve to `resources/views/app.tpl.php`.
     */
    'html_template' => 'inertia::default',

    /**
     * The initial title for the full HTML page.
     */
    'title' => 'Loading...',
];

For vite-specific configurations, create a config file at app/config/packages/inertia/vite.php.

<?php
return [
    /**
     * The path to the manifest file generated by Vite.
     * Only needed if you change the default path in Vite,
     * otherwise the key should be omitted entirely.
     */
    //'manifest' => null,

    /**
     * The path to the hot module replacement file generated
     * by Vite. Only needed if you change the default path in
     * Vite, otherwise the key should be omitted entirely.
     */
    //'hot_file' => null,

    /**
     * The base path for the Vite assets. Should match the
     * `base` option in your Vite configuration, but could
     * also point to a CDN or other asset server, if you are
     * serving assets from a different domain.
     */
    'base_path' => '/build/',
];

Also, configuration for CSRF protection can be defined in app/config/packages/inertia/csrf.php.

<?php
return [
    /*
     * Whether to use the errors prop for token validation
     * errors. By default, an exception will be thrown. If
     * the error should be returned via the Inertia `errors`
     * prop, set this to true.
     */
    'use_errors_prop' => false,

    /*
     * The lifetime of the cookie in seconds. 0 means "until
     * the browser is closed".
     */
    'cookie_ttl' => 0,

    'cookie_options' => [
        /*
         * The path on the server in which the cookie will
         * be available on. If set to '/', the cookie will
         * be available within the entire domain. If set to
         * '/foo/', the cookie will only be available within
         * the /foo/ directory and all sub-directories.
         */
        'path' => '/',

        /*
         * The domain that the cookie is available to. To
         * make the cookie available on all subdomains of
         * example.org (including example.org itself) then
         * you'd set it to '.example.org'.
         */
        'domain' => '',

        /*
         * Indicates that the cookie should only be
         * transmitted over a secure HTTPS connection from
         * the client. When set to TRUE, the cookie will
         * only be set if a secure connection exists. On
         * the server-side, it's on the programmer to send
         * this kind of cookie only on secure connection
         * (e.g. with respect to $this->request->isSecure()).
         */
        'secure' => false,

        /*
         * When TRUE the cookie will be made accessible only
         * through the HTTP protocol. This means that the
         * cookie won't be accessible by scripting languages,
         * such as JavaScript. Since the cookie is likely needed
         * by the JavaScript HTTP library in the frontend, it is
         * highly recommended to set this to FALSE.
         */
        'httponly' => false,

        /*
         * The supported values are 'Lax', 'Strict' and 'None'.
         *
         * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
         */
        'samesite' => 'Lax',
    ],
];

Using a Custom html_template

You will probably want to create your own html_template at some point in your project. You can do so with any renderer of your choosing (other than the InertiaRenderer). For example, to use a standard Mako template, you could create a file at app/resources/views/app.tpl.php, and then update the inertia.php config file to set 'html_template' => 'app'.

There are 3 values passed to the template from the InertiaRenderer. You can add to these using built-in Mako functionality.

  • $title: Just a pass-thru of the title config var above. This is optional to use.
  • $page: The JSON Inertia page object. You have to use this somewhere for Inertia to work.
  • $tags: The HTML tags for Vite resources. It contains three string properties: js, css, and preload. You have to use at least the js property somewhere for Inertia to work.

Here is the default page used in this inertia-mako package:

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <title>{{ $title }}</title>
    {{ raw:$tags->preload }}
    {{ raw:$tags->css }}
    {{ raw:$tags->js }}
</head>
<body>
    <div id="app" data-page="{{ attribute:$page }}"></div>
</body>
</html>

Coding Your App

The idea of this InertiaJS adapter is to utilize existing Mako framework functionality. As such, it's built to have the Vue files be organized under app/resources/views/. Pages should be under the Pages/ folder. For example:

app/
    resources/
        views/
            Components/
                ...
            Layouts/
                ...
            Pages/
                Welcome.vue
                ...

In your routes or controllers, you can use the Mako ViewFactory::render() method to handle the InertiaJS response, prefixing the path with Pages/. e.g. $view->render('Pages/Welcome').

The Inertia class is registered in the Mako dependency injection container under the inertia key. So as an alternative to using the ViewFactory with the path prefix, you call $this->inertia->render('Welcome'). This is just a wrapper around the original method, so there's really no difference under the hood. It's just there for personal preference sake.

Asset Versioning

Inertia.js features asset versioning to mitigate stale client-side caching. To indicate the server-side version, create a file at app/config/packages/inertia/version.php that functions like the following:

<?php
return ['1.0'];

You can make that file do whatever you need to come up with your verison. The only requirement is that it ultimately returns an array with a single string value (the array is requirement is due to how Mako configs work).

Commit Hash Versioning

One common way to version assets is to use the commit hash of the current git commit. You can do this by creating a file at app/config/packages/inertia/version.php that looks like this:

<?php
$head_file = file_get_contents(__DIR__ . '/../../../../.git/HEAD');
if (strpos($head_file, 'ref: ') === 0) {
    $ref_file = trim(substr($head_file, 5));
    if (file_exists(__DIR__.'/../../../../.git/' . $ref_file)) {
        $commit_hash = trim(file_get_contents(__DIR__.'/../../../../.git/' . $ref_file));
    } else {
        // this fallback will only be used if the git commit hash cannot be found.
        // this will cause a full page load on almost every request, so it's not ideal.
        // hopefully this will only be used when you first create your repo, and never again once you've made your first commit.
        $commit_hash = date('YmdHis');
    }
} else {
    $commit_hash = trim($head_file);
}
return [$commit_hash];

This approach checks the filesystem rather than using the git command, so it should work on any system that has a .git directory. If you are using a CI/CD pipeline, you may need to adjust the path to the .git directory.