Skip to content

Inertia.js ​

Inertia.js lets you build a single-page app with server-side routing. Controllers return a page component name and its props instead of JSON for an API. The official Inertia client (Vue, React or Svelte) renders the page and turns links and forms into requests that return JSON, so the browser does not reload.

Megh implements the server side of the Inertia v3 protocol. @meghjs/core does not depend on any frontend package. Your app installs the Inertia client and a bundler, as in any Inertia app.

Quick start ​

Inertia support ships in 0.8.0. Until that is released, use the @next CLI. It creates a working Inertia app with Vite and your choice of framework:

sh
npx @meghjs/cli@next new myapp --inertia     # Vue (default)
npx @meghjs/cli@next new myapp --inertia react  # or svelte
cd myapp
npm run start:dev                            # also runs Vite, with hot module replacement
npx megh make:page Users/Show                # frontend/pages/Users/Show.vue

For an existing project, npx megh add inertia [vue|react|svelte] makes the same changes. See megh add. The rest of this page explains the parts.

Project layout ​

src/                  server code: controllers, services, app.ts
views/app.megh.html   the HTML document for first visits (a server template)
frontend/             browser code, built by Vite
├── app.ts            createInertiaApp() (app.tsx for React)
├── css/
└── pages/            page components: Results.Inertia('Users/Show') → pages/Users/Show.vue
public/build/         Vite's output (generated, not committed)

views/ holds only .megh.html templates and frontend/ only browser code. The Vite page covers frontend/ and the build.

Setup ​

ts
app.useSession(); // validation errors and flash messages; SESSION_SECRET in .env
app.useViews(); // views/app.megh.html
app.useVite(); // serves public/build and provides @vite
app.useInertia();
app.shareInertia("appName", "My App");
OptionDefaultMeaning
rootView"app"View holding the HTML document for first visits
rootId"app"id of the element the client mounts on. Must match id in createInertiaApp()
versionthe Vite build's version with useVite(), else ""Asset version, a string or a function returning one. "" turns version checks off

The configuration belongs to the application. It is not global, so two apps in one process can use different settings.

The root view ​

The root view is a normal Megh view. @vite loads the built JavaScript and CSS, and @inertia prints the page data and the mount element:

html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    @vite('frontend/app.ts')
  </head>
  <body>
    @inertia
  </body>
</html>

@inertia renders:

html
<script data-page="app" type="application/json">{"component":"Home",...}</script>
<div id="app"></div>

The JSON is escaped so that <, > and & cannot appear raw. A prop containing </script> therefore cannot end the element early. The view also receives the page object as page, and session when sessions are on.

Returning a page ​

ts
import { Results, inertia } from "@meghjs/core";

@Get("/users/:id")
show(@Param("id") id: number) {
  return Results.Inertia("Users/Show", { user: this.users.find(id) });
}

app.mapGet("/", () => inertia("Home")); // the same, shorter

A first visit (a normal browser request) gets the root view as HTML. A request from the Inertia client (X-Inertia: true) gets the same page object as JSON, with X-Inertia: true. Both are built from one resolved object, so the two cannot differ:

json
{
  "component": "Users/Show",
  "props": { "appName": "My App", "user": { "id": 42 }, "errors": {} },
  "url": "/users/42?tab=profile",
  "version": "3f9a1c2e"
}

url is the path and query string as the server received them.

Props ​

Props are merged in this order. When two have the same name, the later one wins:

  1. errors: validation errors flashed by the previous request, {} if none
  2. shared props from app.shareInertia()
  3. the route's props

A function prop is called only when the prop is sent:

ts
return Results.Inertia("Users/Index", {
  users: () => this.users.all(),
  stats: () => this.users.stats(), // skipped unless sent
});

Shared props use the same rule. A shared function is called per request with { method, url, headers, session }, so it can read the current user's data:

ts
app.shareInertia("flash", ({ session }) => ({
  success: session?.get("success") ?? null,
}));

A plain shared value is the same object for every request. Do not put per-request data in one.

Partial reloads ​

router.reload({ only: ["stats"] }) on the client sends X-Inertia-Partial-Component, X-Inertia-Partial-Data and/or X-Inertia-Partial-Except. When the component matches the current page, Megh sends only the props the client asked for, plus errors. The other props' functions are not called, so their database queries do not run. Names are matched against top-level prop names only (see the support matrix).

Forms and validation ​

Inertia forms do not get a 422 response. The server flashes the errors to the session and redirects back. The next page then shows them in errors. Megh does this for you when sessions are on:

ts
@Post("/contacts")
store(@Body() body: CreateContactDto, @Session() session: MeghSession) {
  this.contacts.create(body);
  session.flash("success", "Contact added.");
  return Results.Redirect("/contacts", 303);
}

If CreateContactDto fails validation on an Inertia request, Megh flashes { name: "Name must be at least 2 characters." } (the first message for each field) and answers 303 to the Referer. If the Referer is missing or points to another site, it redirects to /. The client's useForm() then shows form.errors.name. If the client sends an X-Inertia-Error-Bag header, the errors go under that name instead.

Errors are flashed, so they appear on the next request only. Each visitor's errors are stored in their own session. Without useSession(), a validation error is a normal 400.

Redirects ​

A 302 after an Inertia PUT, PATCH, DELETE or QUERY request is sent as 303 See Other, so the client follows it with a GET. Redirects for other clients, and after POST, are unchanged.

Asset versioning ​

With app.useVite(), the asset version is a hash of the Vite build manifest, so it changes with every frontend build. On an Inertia GET whose X-Inertia-Version differs from it, Megh answers 409 Conflict with X-Inertia-Location: <current URL>. The client then loads that URL as a full page, so open tabs pick up the new assets. Flashed session data is kept for that reload.

Without Vite, or to use your own value, pass version:

ts
app.useInertia({ version: process.env.BUILD_ID });
app.useInertia({ version: () => readBuildId() }); // called once per request

The version must stay the same throughout a deployment.

Caching ​

Every response from an app with useInertia() includes Vary: X-Inertia, added to any Vary values already set. This stops caches and proxies from serving the HTML page in reply to a JSON request, or the reverse.

Support matrix ​

Coverage of the Inertia v3 protocol in this release:

CapabilityStatus
First visit HTML with page-data script and mount elementSupported
Inertia JSON visits, X-Inertia and Vary headersSupported
Shared and route props, lazy function propsSupported
Asset-version mismatch (409 reload)Supported
302 → 303 after PUT / PATCH / DELETE / QUERYSupported
Session validation errors and error bagsSupported
Partial reloads (only / except, top-level names)Supported
Partial reloads with dot paths (auth.user)Not supported
Deferred, optional, always, merge, once and scroll propsNot supported
X-Inertia-Reset, history encryption / clear historyNot supported
External (Inertia::location) and fragment redirectsNot supported
PrecognitionNot supported
Server-side rendering (SSR)Not supported

Rendering the root view on the server is not Inertia SSR. In SSR, the page component's HTML is rendered on the server, and Megh does not do this. The supported features are tested with the official @inertiajs/vue3 client in the inertia-vue sample.

Errors ​

  • Results.Inertia() without app.useInertia() answers 500 and logs the reason.
  • A missing root view answers 500, like a missing Results.View.
  • @inertia used outside the Inertia root view throws when the view renders.
  • An empty component name, non-object props or an invalid rootId throws right away.

Released under the MIT License.