Inertia
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, and 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 Vite and the Inertia 3 client for your front-end (@inertiajs/react, @inertiajs/vue3 or @inertiajs/svelte, version 3).
Install
Add the package with the CLI:
It does steps 1 to 3 of Set it up by hand: the root view, the config and the provider. Then do steps 4 to 6 (Vite, the built files and the middleware) yourself. The command prints a short list of them. It never overwrites a file, so it is safe to run twice.
Set it up by hand
If you do not use dox add, add the package yourself:
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.
<!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>
2. Config
The config tells Dox where your Vite files are:
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:
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
Set up Vite so it writes a manifest into public/build:
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' },
},
}))
Then start the Inertia app in your entry file:
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:
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:
AppConfig appConfig = AppConfig(
globalMiddleware: <dynamic>[
const SessionMiddleware(),
const CsrfMiddleware(),
HandleInertiaRequests(),
],
// ...
);
SessionMiddlewaregives each request a session. Inertia uses it for validation errors and flash data.CsrfMiddlewarestops cross site form posts. It sets theXSRF-TOKENcookie. The Inertia client reads it and sends it back in theX-XSRF-TOKENheader. You do not write any code for this.HandleInertiaRequestsis yourInertiaMiddleware, see Shared props. With no props to share, useconst InertiaMiddleware().
If only some routes are Inertia pages, you can add them to a router instead, in the same order.
Rendering pages
Call inertia with the request, the page name and the props. The page name is the file in resources/js/Pages, without the extension:
import 'package:dox_core/dox_core.dart';
import 'package:dox_inertia/dox_inertia.dart';
import 'package:my_app/app/models/user/user.model.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 (a link or a form) gets the page as JSON.
A prop can be a function, like users above. It runs only when the prop is sent, and it can give a Future. Props become JSON, so a model or any object with toJson() works. A DateTime becomes ISO text.
Inertia.render(req, 'Users/Index', {...}) does the same as inertia(...).
Shared props
Some props are needed on every page, like the signed in user or the app name. Extend InertiaMiddleware and return them from share. Then add it to globalMiddleware (see Middleware):
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. You can also share from any middleware or controller with Inertia.share(req, {...}).
Global values
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. So 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.
Partial reloads
Sometimes a page only needs new data for one prop. The client can ask for some props only, with router.reload({ only: ['users'] }). Dox then sends only those props, and function props that are not sent do not run.
These helpers change when a prop is sent.
Optional props
Inertia.optional sends the prop only when a partial reload asks for it:
Always props
Inertia.always sends the prop on every request, also on a partial reload that does not ask for it:
Deferred props
A slow prop can make the first visit slow. Inertia.defer leaves it out of the first visit, and the page loads it right after:
Deferred props of the same group load in one request. The default group is default:
Merging props
For infinite scroll, the page should add the new items to the old ones, not replace them. Use Inertia.merge for this:
A deferred prop can merge too:
This table shows when each prop is sent:
| 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 |
Forms and validation errors
A form post needs no extra code for errors. This is how it works:
- The page posts the form:
router.post('/users', data)oruseForm. - The controller validates. The validation fails.
- Dox flashes the errors and the old input to the session, and redirects back.
- The page loads again. It gets the errors in the
errorsprop.
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');
}
The page reads the errors from the form:
const { data, setData, post, errors } = useForm({ name: '', email: '' })
// errors.email holds the message, or is undefined
Every page gets errors, also on a partial reload. It is {} when there are no errors. The old input is in req.session.old('email'). Password fields are not kept.
Error bags
If one page has two forms, the errors of one form should not show on the other. Pass errorBag in the post, like router.post(url, data, { errorBag: 'login' }) or form.post(url, { errorBag: 'login' }). Then the errors are under the bag name: errors.login.email.
Redirects
After a form, redirect with redirect(url) or back(req) from Dox:
Future<DoxResponse> update(DoxRequest req, int id) async {
// ... save the user
return redirect('/users'); // 303 for an Inertia PUT
}
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 requests. You do not need to do anything.
If a controller returns nothing to an Inertia request, InertiaMiddleware sends the browser back to the page it came from, like back(req).
External redirects
To go to an outside site, or any page that is not an Inertia page, use Inertia.location. The client then loads the url with a full page load:
Flash data
Flash data is a short message for the next page, like "User saved". Use Inertia.flash, and 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');
}
Read it on the page:
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 the entry files from the Vite dev server, so you get hot reload. In production, Dox reads public/build/.vite/manifest.json and gives the <link> and <script> tags of the built files.
Dox is in dev mode when devServerUrl is set, or when the file public/hot exists. So set devServerUrl from the env, and production does not use it:
import 'package:dox_core/dox_core.dart';
import 'package:dox_inertia/dox_inertia.dart';
InertiaConfig inertiaConfig = InertiaConfig(
entryPoints: <String>['resources/js/app.jsx'],
devServerUrl: Env.get<String>('APP_ENV') == 'development'
? 'http://localhost:5173'
: null,
reactRefresh: true,
);
Asset version
When you deploy new JavaScript, a browser that is still open has the old files. The asset version fixes this. When the version changes, the next link click loads the whole page again, with the new files.
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, for example 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, so an Inertia request (a link or a form) does not get them. You can call withViewData many times, also in a middleware, and the data is merged.
Each value is HTML escaped. 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.
{{ csrfToken }} is filled for you with the CSRF token of the session. It needs SessionMiddleware.
A {{ key }} that you did not set stays as it is, so set every key that the root view uses.
A title set this way is for the first page load only, because later visits do not load the root view again. There, the <Head> component of the Inertia client changes the title. So set the title in <Head> too.
Another root view for some pages
Sometimes a part of the app needs another HTML page, like an admin area. Inertia.setRootView uses another file for one request:
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, because it could show any file of the server as the page.
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. When you clear the history, the old pages can not be read any more, and the back button 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:
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.
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 Node process 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
Write an entry file for the SSR server:
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:
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, then the SSR file. Then start the SSR server with 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.
Keep the Node process running with your process manager, like the Dox app. Build and start it again on each deploy.
4. Turn it on
Set ssr in the config:
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:
The root view with SSR
The root view needs no change. The HTML from the SSR server goes in place of @inertia. The head tags of the page (from the <Head> component, like <title>) go right before </head>.
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
If 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 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,deepMergePropsandmatchPropsOn. - Partial reloads of nested props with dots, like
only: ['auth.user']. Ask for the top level prop (auth). - Starting the SSR server from Dox. You run the Node process yourself.
Inertia needs sessions for the errors, flash data and redirects. The client sends the CSRF token by itself, see CSRF.
Details
This section is for special cases. Most apps do not need it.
@inertiabecomes<script data-page="app" type="application/json">{"component":"Home",...}</script><div id="app"></div>. In the JSON,<,>and&are written as\u003c,\u003eand\u0026, so a prop can not end the script tag.- An Inertia request has
X-Inertia: true. Its answer hasX-Inertia: trueandVary: X-Inertia. - A Dart
intabove 2^53 in a prop loses precision, because JavaScript reads the page JSON. Send such a number as a string. - The page lists the names of the shared props in
sharedProps. The client keeps them on an instant visit. A prop shared for the request wins over a global one. Inertia.lazyis the same asInertia.optional. A deferred prop with.merge()(ormerge: true) is also listed inmergePropswhen it is sent.- With an error bag, the client sends the
X-Inertia-Error-Bagheader. You do not need to passerrorsyourself, but a page prop namederrorsstill wins. - An empty
200answer to an Inertia request goes back only to aRefererof the same site. Any otherReferergoes to/. A request withoutX-Inertiagets the empty answer as it is. Inertia.locationgives an Inertia request409withX-Inertia-Location. Other requests get302. An old asset version on an InertiaGETalso gets409withX-Inertia-Location.- In dev mode,
@viteloads@vite/clienttoo. WithreactRefresh: trueit adds the React Fast Refresh code first. In production,@vitegives a<link>tag for the css of each entry and of the chunks it imports, and a<script type="module">tag for each entry. public/hotholds the dev server url. Some Vite plugins write it whileviteruns. Dox ignores it only whenAPP_ENVisproduction(in any case), and prints a warning. Other values, likestagingor an empty value, still use it.- Root view data: the escaped characters are
&,<,>,"and'. Anullvalue gives empty text. For the same key, the last call wins. A key has letters, digits and_, and the spaces are optional:{{title}}works too. With no session,{{ csrfToken }}stays as it is. Your owncsrfTokenvalue wins. Only{{ key }}in the root view file is replaced, not the same text in a prop or in the SSR HTML. - With SSR, the
<Head>title is also added to the first page, so use only one ofwithViewDataand<Head>for the title. - Another root view works like the default one, with
@vite,@inertiaand{{ key }}. - History encryption keeps its key in the browser, in session storage. With no session,
clearHistoryonly works when the same request renders a page withinertia(...). - With SSR, head tags need a
</head>tag (</HEAD>works too). A root view with no</head>gets no head tags. The SSR HTML holds the page data and the rendered<div id="app">.