The magic of Inertia is in the server-side responses. When your app first loads, a full html
page is returned. However, all subsequent page visits are done via xhr
, with only json
returned. This allows the single-page app functionality, since Inertia doesn't have to reboot the JavaScript framework on each page load.
Inertia shares page data between the server and the front-end using a page
object. This object includes the necessary information required to render the page component, update the history state, and track the application's asset version.
The page
object includes four attributes:
When an Inertia app first loads, a full html
response is returned from the server. This includes your site assets in the <head>
and a root <div>
in the body.
The root <div>
includes a data-page
attribute with a json
encoded version of the initial page object. Inertia uses this to boot your JavaScript application.
<html>
<head>
<title>My app</title>
<link href="/css/app.css" rel="stylesheet">
<script src="/js/app.js" defer></script>
</head>
<body>
<div id="app" data-page="{"component":"Event","props":{"event":{"id":80,"title":"Birthday party","start_date":"2019-06-02","description":"Come out and celebrate Jonathan's 36th birthday party!"}},"url":"/events/80","version":"c32b8e4965f418ad16eaebba1d4e960f"}"></div>
</body>
</html>
json
encodes the page object into the root <div>
, which is used to boot your JavaScript framework.Since Inertia is a framework for building single-page applications, all subsequent page visits are made as xhr
requests.
Rather than returning a full html
response on subsequent page visits, Inertia simply returns a json
response of the page object. This json
response is in the exact same format as the page object encoded in the initial data-page
attribute.
{
"component": "Event",
"props": {
"event": {
"id": 80,
"title": "Birthday party",
"start_date": "2019-06-02",
"description": "Come out and celebrate Jonathan's 36th birthday party!"
}
},
"url": "/events/80",
"version": "c32b8e4965f418ad16eaebba1d4e960f"
}
All xhr
responses have an X-Inertia
header set to true
. If you're creating your own server-side adapter, you can use this header to detect an Inertia response.
All xhr
responses also include an X-Inertia-Version
header used for auto refreshing assets. You can learn more about that on the asset versioning page.
Finally, all xhr
responses have the Vary
header set to Accept
. This tells the browser that a page can be loaded in two different formats: html
and json
.