Skip to content

Owner and services ​

Pages are rendered with no Ember owner unless you pass one. createOwner builds a lightweight @ember/owner for services and @service injections — with no @ember/application, no Ember router, and no ember-resolver.

Providing services ​

From a folder with import.meta.glob ​

Point createOwner at your services folder the way Ember's strict resolver reads module maps:

ts
// resources/js/app.ts
import { createInertiaApp, createOwner } from 'inertia-ember';

createInertiaApp({
  // ./services/cart.ts      -> `service:cart`      (@service declare cart)
  // ./services/my-cart.ts   -> `service:my-cart`   (@service declare myCart)
  // ./services/auth/jwt.ts  -> `service:auth/jwt`  (@service('auth/jwt') declare jwt)
  owner: () => createOwner(import.meta.glob('./services/**/*.ts', { eager: true })),
});

Services are instantiated lazily on first lookup and cached as singletons on the owner, so their state carries across Inertia visits.

Explicitly (without a glob) ​

Pass a { services } map when you'd rather wire services up by name — classes (Service subclasses or plain ES classes) are instantiated lazily on first lookup, and plain objects are registered as pre-built instances:

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

import CartService from './services/cart.ts';
import JwtService from './services/auth/jwt.ts';

createInertiaApp({
  owner: () =>
    createOwner({
      services: {
        cart: CartService,
        'auth/jwt': JwtService,
        config: { apiBase: '/api' }, // plain object -> registered with { instantiate: false }
      },
    }),
});

You can also combine a glob with services overrides (handy in tests for mocking a single service), or call owner.register(...) directly for non-singleton factories:

ts
const owner = await createOwner({
  modules: import.meta.glob('./services/**/*.ts', { eager: true }),
  services: {
    auth: { user: { name: 'Ada' } }, // overrides ./services/auth.ts
  },
});

owner.register('service:draft', DraftService, { singleton: false });

Writing a service ​

Extending @ember/service ​

Standard Ember services work out of the box, including @tracked state, willDestroy(), getOwner(this), and injecting other services with @service:

ts
// resources/js/services/pricing.ts
import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';

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

export default class PricingService extends Service {
  @service declare cart: CartService;
  @tracked currency = 'USD';

  get summary(): string {
    return `${this.currency} · ${this.cart.items.length} items`;
  }

  willDestroy(): void {
    super.willDestroy();
    // runs automatically when the owner is destroyed
  }
}

Plain classes ​

You don't have to extend Service if you don't need EmberObject. Plain classes receive the owner in their constructor, have setOwner(instance, owner) attached automatically, and can use @service, @tracked, and registerDestructor:

ts
// resources/js/services/clock.ts
import { registerDestructor } from '@ember/destroyable';
import { tracked } from '@glimmer/tracking';

export default class ClockService {
  @tracked now = Date.now();

  constructor() {
    if (typeof window !== 'undefined') {
      const id = window.setInterval(() => (this.now = Date.now()), 1000);
      registerDestructor(this, () => window.clearInterval(id));
    }
  }
}

Using services in pages and layouts ​

Inject any registered service with @service from @ember/service:

gts
// resources/js/pages/Products/Show.gts
import Component from '@glimmer/component';
import { fn } from '@ember/helper';
import { on } from '@ember/modifier';
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>
}

Nested services and non-matching property names take a string name:

ts
@service('auth/jwt') declare jwt: JwtService;
@service('my-cart') declare basket: MyCartService;

TypeScript registry ​

Merge your services into @ember/service's Registry so both @service and getOwner(this)?.lookup('service:…') are typed:

ts
declare module '@ember/service' {
  interface Registry {
    cart: CartService;
    'auth/jwt': JwtService;
  }
}

SSR and lifecycle ​

Pass a function, not an owner instance, to createInertiaApp:

ts
// Both app.ts and ssr.ts
const services = import.meta.glob('./services/**/*.ts', { eager: true });

createInertiaApp({
  owner: () => createOwner(services),
});
  • In the browser, owner() runs once when the app boots. Services live across Inertia visits until app.destroy().
  • On the server, owner() runs once per request and inertia-ember calls owner.destroy() right after rendering that page, so one visitor's service state never leaks to the next and every singleton service's willDestroy() and registerDestructor() callbacks run cleanly.

What works, what doesn't ​

WorksNot included in createOwner
@service in pages, layouts, components, and other services@ember/application, ApplicationInstance, app initializers
Dasherized (myCart → my-cart), nested (auth/jwt), and relative pathsEmber's classic router (service:router, @route)
@ember/service subclasses and plain ES classesLoose-mode template/component/helper resolver lookups
getOwner(this), lookup, factoryFor, register, unregisterClassic EmberObject.inject / implicit owner.inject()
{ singleton: false }, { instantiate: false }, registerOptionsForType
willDestroy() and registerDestructor() teardown on owner.destroy()

If an addon requires a full Ember ApplicationInstance, createInertiaApp's owner option accepts any object with a destroy() method, so you can pass your own owner instead of createOwner.

Demo example ​

The demo keeps the ideas you save in a saved service, and the Ideas page lists them first:

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

import type { Idea } from '../types.ts';

type Saved = Pick<Idea, 'id' | 'title'>;

/**
 * Ideas the visitor saved for later. A service lives as long as the owner, so the list survives every
 * Inertia visit without going to the server; a reload starts it over.
 */
export default class SavedService extends Service {
  @tracked ideas: Saved[] = [];

  has = (id: number): boolean => this.ideas.some((idea) => idea.id === id);

  toggle = (idea: Saved): void => {
    this.ideas = this.has(idea.id)
      ? this.ideas.filter((saved) => saved.id !== idea.id)
      : [...this.ideas, { id: idea.id, title: idea.title }];
  };
}

// `@service declare saved: SavedService` finds it by this name.
declare module '@ember/service' {
  interface Registry {
    saved: SavedService;
  }
}

Released under the MIT License.