Skip to content

Setup ​

The functions that boot the app: createInertiaApp, createOwner for Ember services, and config for Inertia's defaults. The server-side entry, inertia-ember/server, is at the end.

createInertiaApp ​

Boots an Inertia app with Ember components as pages. In the browser it reads the first page from the DOM, renders it (or attaches to the server-rendered HTML) and starts the router. On the server it returns a function that renders one page at a time.

ts
// app.ts
import { createInertiaApp } from 'inertia-ember';

import AppLayout from './layouts/AppLayout.gts';

createInertiaApp({
  layout: () => AppLayout,
  title: (title) => `${title} · My app`,
});

Signature ​

ts
function createInertiaApp(options?: CreateInertiaAppOptions): Promise<{ destroy(): void } | PageRenderer>;

type PageRenderer = (page: Page, render: typeof renderToString) => Promise<{ head: string[]; body: string }>;

In the browser the promise resolves once the first page is on screen, to an object whose destroy() tears the app down. On the server (no window) it resolves to a PageRenderer; see On the server.

Options ​

NameTypeDefaultDescription
resolve(name: string, page: Page) => ResolvedPage | Promise<ResolvedPage>written by @inertiajs/viteLoads the page component the server named. It may return the component or its module ({ default, layout }). Required unless @inertiajs/vite writes it for you.
layout(name: string, page: Page) => unknownnoneThe layout, or layouts, for pages that don't export their own layout. Takes the same values as a page's layout export.
title(title: string, page: Page) => stringnoneFormats every page title, such as the one <Head @title> sets.
progressProgressOptions | false{}The progress bar shown during visits: delay (250 ms), color (#29d), includeCSS (true), showSpinner (false), popover. false turns it off.
defaultsParameters<typeof config.replace>[0]{}Inertia's config defaults: form, prefetch and visitOptions. See config.
ownerAppOwner | (() => AppOwner | Promise<AppOwner>)noneThe Ember owner pages and layouts render with, for @service. Usually () => createOwner(…). See createOwner.
idstring'app'The root element's id. The first page is read from the <script type="application/json"> whose data-page is this id.
pagePageread from the DOMThe first page, when it isn't in the DOM. Browser only: on the server it throws.
serverHeadboolean | string | ((page: Page) => string[] | null | undefined)noneHead tags the server sends as a prop: true reads the head prop, a string names another prop, a function picks them from the page. Each tag is an HTML string.
noncestringnoneA CSP nonce for the <style> tags Inertia adds (the progress bar, the error dialog).
httpHttpClient | HttpClientOptionsInertia's XHR clientA client of your own for Inertia's requests, or options for the default one: xsrfCookieName (XSRF-TOKEN) and xsrfHeaderName (X-XSRF-TOKEN).
liveLiveOptionnoneThe transport for live props, such as echo(instance) from inertia-ember/echo. See Live props.
devbooleanimport.meta.env.DEVTurns on Inertia's development-only integrations.

createInertiaApp throws when there's no resolve, when the root element is missing, or when there's no page data for it.

Examples ​

Resolve pages yourself ​

@inertiajs/vite, with framework from inertia-ember/vite, writes resolve from ./pages/**/*.gts. Without it, point the page name at a file:

ts
import { createInertiaApp } from 'inertia-ember';

const pages = import.meta.glob('./pages/**/*.gts');

createInertiaApp({
  resolve: (name) => pages[`./pages/${name}.gts`]!(),
});

resolve gets the page too, so the choice can depend on it:

ts
createInertiaApp({
  resolve: (name, page) => pages[`./pages/${page.props.mobile ? 'Mobile/' : ''}${name}.gts`]!(),
});

Choose a default layout ​

layout is called with the page's name and the page, for pages that don't export a layout of their own:

ts
import AdminLayout from './layouts/AdminLayout.gts';
import AppLayout from './layouts/AppLayout.gts';

createInertiaApp({
  layout: (name) => (name.startsWith('Admin/') ? [AppLayout, AdminLayout] : AppLayout),
});

Format titles and style the progress bar ​

ts
createInertiaApp({
  title: (title) => (title ? `${title} · Acme` : 'Acme'),
  progress: { color: '#e04e39', delay: 150 },
});

Set Inertia's defaults ​

ts
createInertiaApp({
  defaults: {
    form: { recentlySuccessfulDuration: 5000 },
    prefetch: { cacheFor: '1m', hoverDelay: 150 },
  },
});

Use the head tags the server sends ​

When the server sends the page's head as a list of HTML strings in a prop (head: ['<title>Inbox</title>']), pass serverHead: true and they go to the document head, on the server and on every visit. <Head> can still add to them.

ts
createInertiaApp({ serverHead: true });

// Or from a prop with another name:
createInertiaApp({ serverHead: 'meta' });

createOwner ​

Builds a lightweight @ember/owner (InertiaOwner) from your service modules, the way Ember's strict resolver reads them, with no @ember/application, ember-cli, or ember-resolver. Pass it to createInertiaApp's owner so pages, layouts, and services can use @service.

ts
import { createInertiaApp, createOwner } from 'inertia-ember';

createInertiaApp({
  // ./services/cart.ts becomes `service:cart`, for `@service declare cart` in any page or layout.
  owner: () => createOwner(import.meta.glob('./services/**/*.ts', { eager: true })),
});

Signature ​

ts
type Modules = Record<string, unknown>;
type ServiceEntry = Factory<object> | (new (...args: never[]) => object) | object;

interface CreateOwnerOptions {
  modules?: Modules;
  services?: Record<string, ServiceEntry>;
}

interface InertiaOwner extends Owner {
  readonly isDestroying: boolean;
  readonly isDestroyed: boolean;
  destroy(): void;
  ownerInjection(): object;
  resolveRegistration(fullName: FullName): Factory<object> | object | undefined;
  hasRegistration(fullName: FullName): boolean;
  unregister(fullName: FullName): void;
  registerOptions(fullName: FullName, options: RegisterOptions): void;
  registeredOption<K extends keyof RegisterOptions>(fullName: FullName, optionName: K): RegisterOptions[K] | undefined;
  registeredOptions(fullName: FullName): RegisterOptions | undefined;
  registerOptionsForType(type: string, options: RegisterOptions): void;
  registeredOptionsForType(type: string): RegisterOptions | undefined;
}

function createOwner(modulesOrOptions?: Modules | CreateOwnerOptions): Promise<InertiaOwner>;

Arguments ​

NameTypeDefaultDescription
modulesOrOptionsModules | CreateOwnerOptions{}Either a module map from an eager import.meta.glob (./services/cart.ts → service:cart), or { modules?, services? } where services maps service names to classes or instances.

It resolves to a lightweight InertiaOwner that does not boot @ember/application, keeping Ember's classic router and container out of your bundle and making per-request SSR owners fast. Classes and Ember factories are instantiated lazily on first lookup (via .create(ownerInjection) for @ember/service subclasses or new Class(owner) for plain classes) and destroyed along with their registered destructors when owner.destroy() is called; plain objects in services are registered with { instantiate: false }.

Examples ​

Share state across visits with a service ​

A service lives as long as the owner, so its state carries across Inertia visits:

ts
// services/cart.ts
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';

export default class CartService extends Service {
  @tracked items: string[] = [];

  add = (item: string) => (this.items = [...this.items, item]);
}
gts
// pages/Products/Show.gts
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { fn } from '@ember/helper';
import { service } from '@ember/service';
import type { PageSignature } from 'inertia-ember';

import type CartService from '../../services/cart.ts';

export default class Show extends Component<PageSignature<{ product: { id: string; name: string } }>> {
  @service declare cart: CartService;

  <template>
    <h1>{{@props.product.name}}</h1>
    <button type='button' {{on 'click' (fn this.cart.add @props.product.id)}}>Add to cart</button>
    <p>{{this.cart.items.length}} in the cart</p>
  </template>
}

Provide services by name (without a glob) ​

ts
import { createInertiaApp, createOwner } from 'inertia-ember';
import CartService from './services/cart.ts';

createInertiaApp({
  owner: () =>
    createOwner({
      services: {
        cart: CartService,
        config: { env: 'production' },
      },
    }),
});

Pass a function, not an owner ​

owner takes an owner or a function that returns one. Pass the function: in the browser it's called once, and on the server once per page, then destroyed, so one visitor's service state never reaches the next.

config ​

Inertia's global config, the same object @inertiajs/core exports. createInertiaApp fills it from its defaults option (keys you leave out keep Inertia's defaults); read or change it at runtime with get and set.

ts
import { config } from 'inertia-ember';

config.set('prefetch.cacheFor', '1m');
config.get('form.recentlySuccessfulDuration'); // 2000

Signature ​

ts
config.get(key: string): unknown; // typed by key: 'form.withAllErrors' is a boolean
config.set(key: string, value: unknown): void;
config.set(values: Record<string, unknown>): void; // { 'prefetch.hoverDelay': 100, … }
config.replace(config: object): void; // what `defaults` does

Keys ​

KeyTypeDefaultDescription
form.recentlySuccessfulDurationnumber2000How long, in ms, a form's recentlySuccessful stays true.
form.forceIndicesArrayFormatInFormDatabooleantrueWrites arrays in FormData as tags[0] rather than tags[].
form.withAllErrorsbooleanfalsePrecognition errors keep every message per field (a list), not only the first.
prefetch.cacheFornumber | string | Array<number | string>30000How long a prefetched page stays fresh (30000, '30s', '1m').
prefetch.hoverDelaynumber75How long, in ms, the pointer rests on a link before @prefetch="hover" fires.
noncestringnoneSet by createInertiaApp's nonce.
visitOptions(href: string, options: VisitOptions) => VisitOptionsnoneChanges the options of every visit before it's sent.

Examples ​

Add a header to every visit ​

ts
createInertiaApp({
  defaults: {
    visitOptions: (href, options) => ({
      ...options,
      headers: { ...options.headers, 'X-Client': 'web' },
    }),
  },
});

On the server ​

For server-side rendering, ssr.ts calls createInertiaApp the same way app.ts does. With no window and no page, it resolves to a PageRenderer: a function that renders one page with renderToString from inertia-ember/server and returns { head, body }, what an Inertia SSR server answers with.

ts
// ssr.ts
import { createInertiaApp, createOwner } from 'inertia-ember';

import AppLayout from './layouts/AppLayout.gts';

createInertiaApp({
  layout: () => AppLayout,
  owner: () => createOwner(import.meta.glob('./services/*.ts', { eager: true })),
});

@inertiajs/vite wraps that call for you: in development Vite renders each first page load with it, and the production build starts Inertia's SSR server. Without the plugin, wire it up with the two exports of inertia-ember/server:

ts
// ssr.ts, by hand
import { createInertiaApp, type PageRenderer } from 'inertia-ember';
import createServer, { renderToString } from 'inertia-ember/server';

const pages = import.meta.glob('./pages/**/*.gts');
const app = createInertiaApp({ resolve: (name) => pages[`./pages/${name}.gts`]!() }) as Promise<PageRenderer>;

createServer(async (page) => (await app)(page, renderToString));
ExportFromDescription
renderToStringinertia-ember/serverrenderToString(component, { args?, owner? }) renders a component to { body, heads }: the HTML with Glimmer's rehydration markers, and the tags each <Head> asked for.
createServerinertia-ember/serverThe default export: @inertiajs/core's SSR server. createServer(render, port | { port, host, cluster, formatErrors }).

While rendering on the server, modifiers don't run, router isn't started, polls and remembered state stay inert, and <WhenMounted> shows its fallback.

App ​

The root component createInertiaApp renders: it holds the current page, its layouts, and starts the router. You don't render it yourself; it's exported for renderToString and for its InertiaAppSignature.

Related: Installation, Owner and services, Server-side rendering, Live props, router, Types.

Released under the MIT License.