From https://reinink.ca/articles/introducing-inertia-js
I've recently abandoned server-side rendering entirely in my Laravel projects in favour of a fully Vue.js based front-end. There's a base template, which contains a single div, used as the root Vue.js container. That div has two data attributes, a component name, and component data (props). This is used to tell Vue.js which page component to display, and also provide the data (props) required for it.
<html>
<head>
// …
</head>
<body>
<div id="app" data-component="{{ $component }}" data-props="{{ json_encode($props) }}"></div>
</body>
</html>
Now just use the base template with what component and data you want to render:
Example from the Introduction to Inertia.js:
class EventsController extends Controller
{
public function show(Event $event)
{
return View::make('app', [
'component' => 'Event',
'props' => [
'event' => $event->only('id', 'title', 'start_date', 'description'),
],
]);
}
How does it work on the client side:
We don't want to return the entire base template. Instead, we only want to return the component name and props as JSON.
This is possible by checking for the X-Inertia header:
if (Request::header('X-Inertia')) {
return Response::json([
'component' => $component,
'props' => $props,
'url' => Request::getRequestUri(),
], 200, [
'Vary' => 'Accept',
'X-Inertia' => true,
]);
}
return View::make('app', [
'component' => $component,
'props' => $props,
]);
This header is also included on the response, and we can add the url so we can handle redirects.
However, my goal is to ship helper libraries for popular server-side frameworks. For example, in Laravel all you'll need to do is call Inertia::render() in your controller!
// Synchronously
Inertia::share('app.name', Config::get('app.name'));
// Lazily
Inertia::share('auth.user', function () {
if (Auth::user()) {
return [
'id' => Auth::user()->id,
'first_name' => Auth::user()->first_name,
'last_name' => Auth::user()->last_name,
];
}
});