PHPackages                             rareform/craft-inertia - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rareform/craft-inertia

ActiveCraft-plugin[Utility &amp; Helpers](/categories/utility)

rareform/craft-inertia
======================

Inertia.js adapter for Craft CMS

1.1.0(7mo ago)171302[1 PRs](https://github.com/RareFormLabs/craft-inertia/pulls)MITPHPPHP ^8.2CI passing

Since Dec 18Pushed 7mo ago2 watchersCompare

[ Source](https://github.com/RareFormLabs/craft-inertia)[ Packagist](https://packagist.org/packages/rareform/craft-inertia)[ RSS](/packages/rareform-craft-inertia/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (21)Used By (0)

Inertia.js Craft CMS Adapter
============================

[](#inertiajs-craft-cms-adapter)

[![image](https://private-user-images.githubusercontent.com/1377169/396731791-97f925a2-74c8-4cc6-ad47-c4cdaafe915d.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzQ4ODk5NjgsIm5iZiI6MTc3NDg4OTY2OCwicGF0aCI6Ii8xMzc3MTY5LzM5NjczMTc5MS05N2Y5MjVhMi03NGM4LTRjYzYtYWQ0Ny1jNGNkYWFmZTkxNWQucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI2MDMzMCUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNjAzMzBUMTY1NDI4WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9ZDg3Y2U1YjViNjE4NTAwOTNiYmZhMDFhZTVkYjMyYTg1ZmYxYzViMzE1NTVjZTFkMmIyNTY2MmEzYmMxYWIyNyZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QifQ.YYZOQkaN4VnwdryCLk4wcdbInaK-Oje09WD-F7Dk5Iw)](https://private-user-images.githubusercontent.com/1377169/396731791-97f925a2-74c8-4cc6-ad47-c4cdaafe915d.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzQ4ODk5NjgsIm5iZiI6MTc3NDg4OTY2OCwicGF0aCI6Ii8xMzc3MTY5LzM5NjczMTc5MS05N2Y5MjVhMi03NGM4LTRjYzYtYWQ0Ny1jNGNkYWFmZTkxNWQucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI2MDMzMCUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNjAzMzBUMTY1NDI4WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9ZDg3Y2U1YjViNjE4NTAwOTNiYmZhMDFhZTVkYjMyYTg1ZmYxYzViMzE1NTVjZTFkMmIyNTY2MmEzYmMxYWIyNyZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QifQ.YYZOQkaN4VnwdryCLk4wcdbInaK-Oje09WD-F7Dk5Iw)

This is a server-side adapter for [Inertia](https://inertiajs.com) built with Craft CMS workflow simplicity in mind.

It utilizes Craft's routing, as well as *Twig* for crafting Inertia responses, rather than requiring they be written directly in PHP (as a traditional Inertia application does).

[Ping CRM Demo](https://pingcrm.rareformlabs.com) — [Ping CRM Repo](https://github.com/rareformlabs/pingcrm)

Requirements
------------

[](#requirements)

This plugin requires Craft CMS 5.4.0 or later, and PHP 8.2 or later.

Installation
------------

[](#installation)

You can install this plugin from the Plugin Store or with Composer.

#### From the Plugin Store

[](#from-the-plugin-store)

Go to the Plugin Store in your project’s Control Panel and search for “Inertia”. Then press “Install”.

#### With Composer:

[](#with-composer)

Open your terminal and run the following commands:

```
composer require rareform/craft-inertia
php craft plugin/install inertia
```

Be sure to follow the installation instructions for the [client-side framework](https://inertiajs.com/client-side-setup) you use.

Note

Upon installing, the Inertia adapter will takeover all routing and expect all templates to respond with inertia protocol responses. To prevent this, you may set the `takeoverRouting` [config option](#configuration) to `false`

Important

Required Reading
----------------

[](#required-reading)

The [Inertia documentation](https://inertiajs.com) is a must-read to understand the protocol, the responsibilities of this adapter, and how to use Inertia on the client-side. The following sections will explain how to use this adapter, but assume you have a basic understanding of Inertia.

Defining Pages
--------------

[](#defining-pages)

Every page in your javascript application is backed by a Twig template which returns a [page object](https://inertiajs.com/the-protocol#the-page-object). The page object defines which page component to render, and what prop data is received.

```
{# templates/posts/index.twig #}

{{ prop('posts', craft.entries.section('posts').limit(20).all()|map(post => {
    title: post.title,
    body: post.body
})) }}

{# Or use the prune filter #}
{{ prop('posts', craft.entries.section('posts').limit(20).all()|prune(['title','body'])) }}

{# Use the page variable to define the Page component to render and props to pass #}
{{ page('Posts/Index') }}
```

Note: templates are passed element variables (`entry` or `category`) automatically when the route is matched to either element type.

Shared Data
-----------

[](#shared-data)

Shared data will automatically be passed as props to your application, sparing you the cumbersome tasks of redefining the same prop data in every page response. You can optionally separate any shared data logic into multiple files for organization.

Create a `_shared` directory at the root of your `/templates` directory:

```
{# templates/_shared/index.twig #}

{{ prop('flashes', craft.app.session.getAllFlashes(true)) }}

{# Not typically necessary #}
{{ prop('csrfTokenName', craft.app.config.general.csrfTokenName) }}
{{ prop('csrfTokenValue', craft.app.request.csrfToken) }}
```

You may want to separate shared data logic or cache to reduce unnecessary repetitive queries:

```
{# templates/_shared/current-user.twig #}

{% if currentUser %}
  {% cache using key currentUser.email %}
    {% set user = {
      id: currentUser.id,
      fullName: currentUser.fullName,
      email: currentUser.email,
    } %}
    {{ prop('currentUser', user) }}
  {% endcache %}
{% else %}
  {{ prop('currentUser', null) }}
{% endif %}
```

### Prune Filter

[](#prune-filter)

You're inevitably going to have some large objects that you don't want to pass to your frontend. You can use the `prune` filter or function to remove properties from objects that are passed to your Inertia component.

```
{# Basic usage: simply pass an array of fields #}
{{ prop('post', craft.entries.section('blog').all()|prune(["title", "author", "body", "url", "featuredImage"])) }}

{# Advanced object syntax #}
{{ prop('post', craft.entries.section('blog').all()|prune(
  {
    title: true,
    id: true,
    uri: true,

    author: ["username", "email"],

    mainImage: {
      url: true,
      uploader: {

        email: true,
        username: true,
      },
    },

    contentBlocks: {

      "$limit": 10,

      _body: {
        body: true,
        intro: true,
      },
      _fullWidthImage: {
        image: ["url", "alt"],
      },
    },
  }
)) }}
```

Pull in Variables
-----------------

[](#pull-in-variables)

Use the `pull` tag to include variables from a specified template and make them available in the current response twig file.

```
{# teams/_base.twig #}
{% set teamColor = "#EE4B2B" %}
```

```
{# templates/teams/_entry.twig #}
{% pull('teams/_base') %}

{{ page('Teams/Entry') }}
{{ prop('teamColor', teamColor) }}
```

This is a simple DX alternative to using `extends` and `block` tags to share variables across templates. Note that the `pull` tag is only available in Inertia responses.

Saving Data
-----------

[](#saving-data)

Craft CMS does not use traditional POST, PUT, PATCH, and DELETE requests for saving data, and instead uses the `action` parameter to when POSTing to various internal Craft controllers. This means saving data to Craft CMS data is a little different than what is expected in a traditional Inertia application.

Here's an example of how you could save an entry using Inertia's `useForm` helper **without** using the adapter's javascript helper:

```
const form = useForm({
  sectionId: 1,
  typeId: 2,
  CRAFT_CSRF_TOKEN: csrf.value,
  action: "entries/save-entry",
  title: "My New Post",
  fields: {
    customField: "My Custom Field Value",
  },
});

const saveEntry = () => {
  // Don't specify a POST url, as we're using the action parameter
  form.post("", {
    // Force the request to use form data in order for Craft to process the request
    forceFormData: true,
  });
};
```

Attaching the CSRF token, the action param, and the `forceFormData` option is required for Craft to process the request correctly, **but it's recommended to use the adapter's helper to remove this repetitive boilerplate.**

### Using the Adapter's Helper

[](#using-the-adapters-helper)

The adapter will automatically attach the CSRF token, action param, and set the `forceFormData` option to `true` for you, but needs access to the same Axios instance used by Inertia's native library.

For the majority of projects, all that's needed on your end is to attach Axios to the window object. The adapter will take care of the rest. (Having issues? Visit troubleshooting section below)

```
import axios from "axios";
window.axios = axios;
```

```
const form = useForm({
  title: "My New Post",
  sectionId: 1,
  typeId: 2,
  fields: {
    customField: "My Custom Field Value",
  },
});

const saveEntry = () => form.post("entries/save-entry");
```

This looks much better. You can optionally reduce one extra step the helper takes by rendering the CSRF token info in your base template's head:

```

```

This extra step reduces additional fetch requests to Craft's sessions endpoint to get the CSRF token manually for unauthenticated users.

Configuration
-------------

[](#configuration)

Create an `inertia.php` file in your Craft `/config` directory. Shown are the default values:

```
