Skip to content

About

Inertia.js adapter for the Dox framework: build React, Vue or Svelte apps without an API layer.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dox_inertia

Inertia.js for the Dox framework: build single page apps with React, Vue or Svelte and Dox controllers, with no API to write.

Inertia lets you build a single page app with React, Vue or Svelte, and keep routes and controllers in Dox.

You do not write an API. A controller gives a page name and its props. Inertia shows the page in the browser. The first visit gets a full HTML page. After that, links and forms get only JSON, and the page changes without a reload.

The dox_inertia package is the server side of Inertia. Use it with the Inertia 3 client for your front-end (@inertiajs/react, @inertiajs/vue3 or @inertiajs/svelte, version 3) and Vite.

Install

dart pub add dox_inertia

Set up

1. Root view

The root view is the HTML page of the first visit. Dox puts the script and style tags in place of @vite, and the page in place of @inertia. It is plain HTML, with no template engine. It can hold {{ key }} marks for values like the title, see Root view data.

resources/views/app.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My app</title>
    @vite
  </head>
  <body>
    @inertia
  </body>
</html>

@inertia becomes the page data and the element the app renders into:

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

This is the format of the Inertia 3 client. In the JSON, <, > and & are written as \u003c, \u003e and \u0026, so a prop can not end the script tag.

2. Config

lib/config/inertia.dart:

import 'package:dox_inertia/dox_inertia.dart';

InertiaConfig inertiaConfig = InertiaConfig(
  /// the Vite entry files
  entryPoints: <String>['resources/js/app.jsx'],

  /// load the scripts from the Vite dev server. null in production.
  devServerUrl: 'http://localhost:5173',

  /// add the React Fast Refresh code in dev mode
  reactRefresh: true,
);
Option Default What it does
rootView resources/views/app.html the HTML page of the first visit. One request can use another file with Inertia.setRootView
entryPoints ['resources/js/app.js'] the Vite entry files
publicPath public the folder of public files
buildDirectory build the folder in publicPath where vite build writes its files
devServerUrl null the url of the Vite dev server, see Vite
reactRefresh false add the React Fast Refresh code in dev mode
version hash of the manifest the asset version, see Asset version
encryptHistory false encrypt the browser history of every page, see History encryption
ssr null server side rendering, see SSR

Paths are from the project root, where the app runs.

3. Provider

The provider sets up Inertia in every isolate. Put it in lib/ so the generated container finds it.

lib/providers/inertia_provider.dart:

import 'package:dox_inertia/dox_inertia.dart';

import '../config/inertia.dart';

class AppInertiaProvider extends InertiaProvider {
  AppInertiaProvider() : super(inertiaConfig);
}

With no provider, Dox uses the defaults of InertiaConfig.

4. Vite

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig(({ command }) => ({
  plugins: [react()],
  // public/ holds the Dox public files. The build goes into public/build,
  // so do not let Vite copy public/ into the build.
  publicDir: false,
  // the built files are served from /build/
  base: command === 'build' ? '/build/' : '/',
  server: { origin: 'http://localhost:5173' },
  build: {
    manifest: true,
    outDir: 'public/build',
    rollupOptions: { input: 'resources/js/app.jsx' },
  },
}))

resources/js/app.jsx:

import { createInertiaApp } from '@inertiajs/react'
import { createRoot } from 'react-dom/client'

createInertiaApp({
  resolve: (name) => {
    const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
    return pages[`./Pages/${name}.jsx`]
  },
  setup({ el, App, props }) {
    createRoot(el).render(<App {...props} />)
  },
})

5. Serve the built files

In production the browser loads /build/assets/.... Add a route for them, or let your proxy (nginx, Caddy) serve public/build.

lib/routes/web.dart:

Route.get('/build/{path*}', (String path) {
  if (path.contains('..')) throw NotFoundHttpException();
  // the file names have a hash, so the browser can keep them for a year
  return response(File('public/build/$path')).cache(const Duration(days: 365));
});

6. Middleware

Add three middleware to globalMiddleware, in this order:

lib/config/app.dart:

AppConfig appConfig = AppConfig(
  globalMiddleware: <dynamic>[
    const SessionMiddleware(),
    const CsrfMiddleware(),
    HandleInertiaRequests(),
  ],
  // ...
);
  • SessionMiddleware gives each request a session. Inertia uses it for validation errors and flash data.
  • CsrfMiddleware stops cross site form posts. It sets the XSRF-TOKEN cookie. The Inertia client reads it and sends it back in the X-XSRF-TOKEN header. You do not write any code for this.
  • HandleInertiaRequests is your InertiaMiddleware, see Shared props. With no props to share, use const InertiaMiddleware().

You can also add them to a router, in the same order, if only some routes are Inertia pages.

Render a page

Give the request, the page name and the props. The page name is the file in resources/js/Pages, without the extension.

lib/app/http/controllers/user.controller.dart:

import 'package:dox_core/dox_core.dart';
import 'package:dox_inertia/dox_inertia.dart';

@Inject()
class UserController {
  Future<DoxResponse> index(DoxRequest req) {
    return inertia(req, 'Users/Index', <String, dynamic>{
      'title': 'Users',
      'users': () => User().query().all(),
    });
  }
}
  • A normal request gets the root view as HTML.
  • An Inertia request (X-Inertia: true) gets the page as JSON, with X-Inertia: true and Vary: X-Inertia.

A prop can be a function, like users above. It runs only when the prop is sent. It can give a Future. Props become JSON. A model or any object with toJson() works. A DateTime becomes ISO text. A Dart int above 2^53 in a prop loses precision. JavaScript reads the page JSON, in the browser and on the SSR server. Send such a number as a string. Inertia.render(req, 'Users/Index', {...}) does the same as inertia(...).

Shared props

Shared props go to every page, like the signed in user or the app name. Extend InertiaMiddleware and add it to globalMiddleware (see Middleware).

lib/app/http/middleware/handle_inertia_requests.dart:

import 'package:dox_core/dox_core.dart';
import 'package:dox_inertia/dox_inertia.dart';

class HandleInertiaRequests extends InertiaMiddleware {
  @override
  Map<String, dynamic> share(DoxRequest req) {
    return <String, dynamic>{
      'appName': 'My app',
      'auth': () => req.auth?.toJson(),
    };
  }
}

A page prop with the same name wins over a shared prop. share can be async. The page lists the names of the shared props in sharedProps. The client keeps them on an instant visit. You can also share from any middleware or controller with Inertia.share(req, {...}).

For a value that is the same for the whole app, use Inertia.shareGlobal(key, value). Call it once in the setup() of your InertiaProvider, so it runs in every isolate:

class AppInertiaProvider extends InertiaProvider {
  AppInertiaProvider() : super(inertiaConfig);

  @override
  void setup() {
    super.setup();
    Inertia.shareGlobal('appName', 'Dox');
  }
}

A global value is kept for all users and all requests. Use it only for a constant, or a function that does not read a request. Data of one user, like the signed in user, must go in InertiaMiddleware.share. A prop shared for the request wins over a global one.

Partial reloads

The client can ask for some props only: router.reload({ only: ['users'] }). Dox reads the headers and sends only those props. Function props that are not sent do not run.

Four helpers change when a prop is sent:

return inertia(req, 'Users/Index', <String, dynamic>{
  /// only when a partial reload asks for it
  'stats': Inertia.optional(() => Stats.load()),

  /// on every request, also on a partial reload that does not ask for it
  'notices': Inertia.always(notices),

  /// not on the first visit: the page loads it right after
  'comments': Inertia.defer(() => Comment().query().all()),
  'likes': Inertia.defer(() => Like().query().count(), group: 'side'),

  /// deferred, and the page adds the new items to the old ones
  'feed': Inertia.defer(() => Post().query().all()).merge(),

  /// the page adds the new items to the old ones (infinite scroll)
  'posts': Inertia.merge(posts),
});
Helper First visit Partial reload
plain value or function sent sent when asked
Inertia.optional not sent sent when asked
Inertia.always sent always sent
Inertia.defer not sent, listed in deferredProps sent when asked
Inertia.merge sent, listed in mergeProps sent when asked

Deferred props of the same group load in one request. The default group is default. Inertia.lazy is the same as Inertia.optional. A deferred prop with .merge() (or merge: true) is also listed in mergeProps when it is sent.

Forms and validation errors

A form post needs no extra code for errors. The flow is:

  1. The page posts the form: router.post('/users', data) or useForm.
  2. The controller validates. The validation fails.
  3. Dox flashes the errors and the old input to the session, and redirects back.
  4. The page loads again. It gets the errors in the errors prop.
Future<DoxResponse> store(DoxRequest req) async {
  await req.validateSchema(
    v.object(<String, Schema<Object?>>{
      'name': v.string().min(2),
      'email': v.string().email(),
    }),
  );
  // ... save the user
  return redirect('/users');
}
const { data, setData, post, errors } = useForm({ name: '', email: '' })
// errors.email holds the message, or is undefined

Every page gets errors. It is {} when there are no errors. It is sent on every request, also on a partial reload. The old input is in req.session.old('email'). Password fields are not kept.

With router.post(url, data, { errorBag: 'login' }) or form.post(url, { errorBag: 'login' }), the client sends the X-Inertia-Error-Bag header. Then the errors are under the bag name: errors.login.email. Use it when one page has two forms.

You do not need to pass errors yourself. A page prop named errors still wins.

Redirects

After a form, redirect with redirect(url) or back(req) from Dox.

After PUT, PATCH or DELETE, the browser must follow the redirect with GET, not with the same method. So InertiaMiddleware turns a 302 into 303 for these Inertia requests. You do not need to do anything.

When a controller gives an empty 200 answer to an Inertia request (eg. it returns nothing), InertiaMiddleware sends the browser back to the page it came from, like back(req). Only a Referer of the same site is used. Any other Referer goes to /. A request without X-Inertia gets the empty answer as it is.

Future<DoxResponse> update(DoxRequest req, int id) async {
  // ... save the user
  return redirect('/users'); // 303 for an Inertia PUT
}

To go to an outside site, or any page that is not an Inertia page, use Inertia.location. An Inertia request gets 409 with X-Inertia-Location, and the client loads the url with a full page load. Other requests get 302.

return Inertia.location(req, 'https://checkout.example.com/pay/1');

Flash data

Flash data is a short message for the next page, like "User saved". Use Inertia.flash. The next page gets it in page.flash, once.

Future<DoxResponse> store(DoxRequest req) async {
  // ... save the user
  Inertia.flash(req, 'message', 'User saved');
  return redirect('/users');
}
import { usePage } from '@inertiajs/react'

const { flash } = usePage()
// flash.message is 'User saved'

The client also fires a flash event, and calls the onFlash callback of the visit. Inertia.flash needs SessionMiddleware.

Vite

In dev mode, @vite loads @vite/client and the entry files from the Vite dev server. With reactRefresh: true it adds the React Fast Refresh code first.

Dox is in dev mode when:

  • devServerUrl is set, or
  • the file public/hot exists. Its text is the dev server url. Some Vite plugins write this file while vite runs. Dox ignores this file only when APP_ENV is exactly production, and prints a warning. Other values, like staging or an empty value, still use it.

In production (no dev server), Dox reads public/build/.vite/manifest.json. @vite gives a <link> tag for the css of each entry and of the chunks it imports, and a <script type="module"> tag for each entry.

Set devServerUrl from the env, so production does not use it. A new Dox app has APP_ENV=development. The vite.config.js above writes no public/hot file, so in dev Dox needs devServerUrl:

lib/config/inertia.dart:

InertiaConfig inertiaConfig = InertiaConfig(
  entryPoints: <String>['resources/js/app.jsx'],
  devServerUrl: <String>['development', 'local'].contains(Env.get<String>('APP_ENV'))
      ? 'http://localhost:5173'
      : null,
  reactRefresh: true,
);

Asset version

Each page has a version. When you deploy new assets, the version changes. A browser with the old version that makes an Inertia GET request gets 409 with X-Inertia-Location. The client then loads the whole page again, with the new assets. InertiaMiddleware sends the 409 before the controller runs. The flash data is kept for the next request, so a flash message is not lost.

The default version is a hash of the Vite manifest. Dox reads it once per isolate, so restart the server after vite build (a deploy does this). To set your own, use version in the config, eg. the git commit.

Root view data

Page props go to the JavaScript page. Sometimes the root view itself needs a value, like the <title> or a CSRF meta tag. Use Inertia.withViewData for that.

Write {{ key }} in the root view:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrfToken }}">
    <title>{{ title }}</title>
    @vite
  </head>
  <body>
    @inertia
  </body>
</html>

Set the values in the controller:

Future<DoxResponse> index(DoxRequest req) {
  Inertia.withViewData(req, <String, Object?>{'title': 'Users'});
  return inertia(req, 'Users/Index', <String, dynamic>{
    'users': () => User().query().all(),
  });
}
  • The values are for the root view only. They are not page props. They are never sent as JSON, so an Inertia request (a link or a form) does not get them.
  • Each value is HTML escaped (&, <, >, " and '). A null value gives empty text.
  • Put a value in text or in a quoted attribute only. It is not safe inside a <script> block, an unquoted attribute or a link address.
  • You can call withViewData many times, also in a middleware. The data is merged. For the same key, the last call wins.
  • A key has letters, digits and _. The spaces are optional: {{title}} works too.
  • {{ key }} with a key that you did not set stays as it is. So set every key that the root view uses.
  • {{ csrfToken }} is filled for you with the CSRF token of the session. It needs SessionMiddleware. With no session it stays as it is. Your own csrfToken value wins.
  • Only {{ key }} in the root view file is replaced. The same text in a prop, or in the HTML from the SSR server, is not touched.

A title set this way is for the first page load only. On later visits the browser does not load the root view again. There, the <Head> component of the Inertia client changes the title. So set the title in <Head> too. With SSR, the <Head> title is also added to the first page, so use only one of the two for the title.

Another root view for some pages

Inertia.setRootView uses another HTML file for one request, eg. for an admin area:

Future<DoxResponse> dashboard(DoxRequest req) {
  Inertia.setRootView(req, 'resources/views/admin.html');
  return inertia(req, 'Admin/Dashboard');
}

RootViewMiddleware does the same for every page of a router:

class AdminRouter extends Router {
  @override
  List<dynamic> get middleware => <dynamic>[
    const RootViewMiddleware('resources/views/admin.html'),
  ];

  // ...
}

The path is from the project root, like rootView in the config. Use a fixed path. Never pass a value from the request: it could show any file of the server as the page. The file works like the default root view, with @vite, @inertia and {{ key }}.

History encryption

The browser keeps the props of each page in its history, so the back button is fast. After a logout, the back button can still show a page with private data. History encryption stops this.

With it, the browser encrypts the page data before it goes into the history. The key stays in the browser, in session storage. When you clear the history, the browser makes a new key, and the old pages can not be read any more. The back button then asks the server for the page again.

The browser can only encrypt on HTTPS, and on localhost.

Turn it on for all pages in the config:

lib/config/inertia.dart:

InertiaConfig inertiaConfig = InertiaConfig(
  encryptHistory: true,
);

Or for one page, in the controller. false turns it off for one page when the config turns it on.

Future<DoxResponse> show(DoxRequest req) {
  Inertia.encryptHistory(req);
  // Inertia.encryptHistory(req, false);
  return inertia(req, 'Account/Show', props);
}

Or for all pages of a router, with EncryptHistoryMiddleware:

class AccountRouter extends Router {
  @override
  List<dynamic> get middleware => <dynamic>[const EncryptHistoryMiddleware()];

  // ...
}

Call Inertia.clearHistory(req) to clear the history, for example on logout:

Future<DoxResponse> logout(DoxRequest req) async {
  // ... sign the user out
  Inertia.clearHistory(req);
  return redirect('/login');
}

The next Inertia page tells the browser to clear its history, once. The mark is kept in the session, so it works with a redirect. It needs SessionMiddleware. With no session, it only works when the same request renders a page with inertia(...).

Server side rendering (SSR)

By default, the first visit gets an empty page, and the browser renders it. With SSR, the first visit gets the full HTML of the page. Search engines can read it, and the visitor sees the page sooner.

The page is rendered by the Inertia SSR server. It is a JavaScript process (Bun or Node) that you build with Vite and run next to your Dox app. On a first visit, Dox sends the page to it and puts the answer in the root view. Inertia requests (links and forms) never use it.

1. The SSR entry file

dox inertia:install --ssr writes resources/js/ssr.jsx for you, and adds a build:ssr script to package.json. It never overwrites a file. With no package.json (or one it cannot change safely), it prints a hint instead.

{
  "scripts": {
    "build:ssr": "vite build && vite build --ssr resources/js/ssr.jsx --outDir bootstrap/ssr"
  }
}

Without --ssr, add the build:ssr line to scripts yourself, and write the entry file like this:

import { createInertiaApp } from '@inertiajs/react'
import createServer from '@inertiajs/react/server'
import ReactDOMServer from 'react-dom/server'

createServer(
  (page) =>
    createInertiaApp({
      page,
      render: ReactDOMServer.renderToString,
      resolve: (name) => {
        const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
        return pages[`./Pages/${name}.jsx`]
      },
      setup: ({ App, props }) => <App {...props} />,
    }),
  { host: '127.0.0.1' },
)

Vue and Svelte have the same createServer, in @inertiajs/vue3/server and @inertiajs/svelte/server.

The SSR server listens on port 13714. Set host to 127.0.0.1, so only your own machine can reach it.

2. Hydrate in the browser

The browser must reuse the HTML from the server, and not render the page again. Change setup in your app file:

resources/js/app.jsx:

import { createInertiaApp } from '@inertiajs/react'
import { createRoot, hydrateRoot } from 'react-dom/client'

createInertiaApp({
  resolve: (name) => {
    const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
    return pages[`./Pages/${name}.jsx`]
  },
  setup({ el, App, props }) {
    if (el.hasAttribute('data-server-rendered')) {
      hydrateRoot(el, <App {...props} />)
    } else {
      createRoot(el).render(<App {...props} />)
    }
  },
})

The else part is for a page that was sent without SSR.

3. Build and run

Build the browser files and the SSR file, then start the SSR server:

bun run build:ssr
dox inertia:start-ssr

dox inertia:start-ssr runs bootstrap/ssr/ssr.js (or ssr.mjs) with Bun, in the foreground. When both files exist, it starts the newer one and prints which. It stops with an error when the file is not built yet. A stop signal (Ctrl+C, docker stop) is sent on to the SSR process.

With Node, use npm run build:ssr and dox inertia:start-ssr --node.

The file is ssr.js when your package.json has "type": "module". Else it is ssr.mjs. The SSR file loads your packages from node_modules, so keep that folder on the server.

The command does not run in the background. Run it under Docker, pm2 or systemd, like the Dox app. Build and start it again on each deploy.

4. Turn it on

lib/config/inertia.dart:

InertiaConfig inertiaConfig = InertiaConfig(
  entryPoints: <String>['resources/js/app.jsx'],
  ssr: InertiaSsr(),
);

With no ssr, SSR is off. InertiaSsr has two options:

Option Default What it does
url http://127.0.0.1:13714/render the render url of the SSR server
timeout 2 seconds how long Dox waits for the answer. Then it stops the request.

The url must be a full http or https url. A wrong url gives an error when the app starts.

To use SSR only in production, set it from the env:

ssr: Env.get<String>('APP_ENV') == 'production' ? InertiaSsr() : null,

The root view with SSR

The root view needs no change. It must have @inertia. Head tags also need a </head> tag.

  • The HTML from the SSR server goes in place of @inertia. It holds the page data and the rendered <div id="app">.
  • The head tags of the page (from the <Head> component, like <title>) go right before the first </head>. </HEAD> works too. A root view with no </head> gets no head tags.

When your pages set a title with <Head>, remove the <title> from the root view, so the page does not have two.

When the SSR server fails

When the SSR server is down, is too slow, or gives a bad answer, the visitor gets the normal page and the browser renders it. No error is shown. Dox prints one warning to stderr for the first failure, and no more until the SSR server works again.

Not included

  • The Inertia 1 and 2 clients. They read the page from <div id="app" data-page="...">. Use the Inertia 3 client.
  • Once props, scroll props (infinite scroll), prependProps, deepMergeProps and matchPropsOn.
  • Partial reloads of nested props with dots, like only: ['auth.user']. Ask for the top level prop (auth).

About

Inertia.js adapter for the Dox framework: build React, Vue or Svelte apps without an API layer.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages