Skip to main content

luxid_core/
inertia.rs

1//! The server half of the [Inertia.js](https://inertiajs.com) protocol.
2//!
3//! Inertia lets a React/Vue/Svelte frontend be driven by ordinary server-side
4//! routing and controllers: no API client, no client-side router, no token
5//! juggling. The official client adapters work against any backend that speaks
6//! the protocol, so Luxid only has to implement this half.
7//!
8//! # The protocol, in full
9//!
10//! | Condition | Response |
11//! |---|---|
12//! | no `X-Inertia` header | an HTML shell containing `<div id="app" data-page="…">` |
13//! | `X-Inertia: true` | JSON `{component, props, url, version}` + `X-Inertia: true` |
14//! | `X-Inertia-Version` stale on a GET | `409` + `X-Inertia-Location`, forcing a hard reload |
15//! | `X-Inertia-Partial-Data` present | as above, with `props` filtered to the named keys |
16//! | validation failure | `303` back to the previous page, errors flashed to the session |
17//!
18//! That last row is the one that shapes everything else. Inertia is built on
19//! post-redirect-get: a failed form does not render an error document, it
20//! bounces back to the page it came from and the errors arrive as a prop.
21//!
22//! # Why this is middleware rather than error handling
23//!
24//! The obvious place to turn a validation failure into a redirect is Luxid's
25//! error renderer. It cannot work there: by the time `write_error` runs, the
26//! `HttpContext` — and with it the `Session` the errors must be flashed to —
27//! has already been consumed by the middleware chain.
28//!
29//! [`Inertia`] therefore does what [`crate::auth::SessionGuard`] does: it keeps
30//! a handle to the session on the way in, and converts the failure into a
31//! response on the way out.
32//!
33//! # Ordering matters
34//!
35//! `Auth::session()` must sit **outside** this middleware:
36//!
37//! ```ignore
38//! r.middleware((Auth::session(), Inertia::new("resources/js/app.jsx")));
39//! ```
40//!
41//! The session guard persists on the way out with `next.run(ctx).await?`, so an
42//! `Err` never reaches its write-back. This middleware converts the `Err` into
43//! an `Ok(redirect)` first, which is what lets the flashed errors survive.
44//! Reversed, the flash would be written and then silently dropped.
45//!
46//! # What this does not change
47//!
48//! Nothing about [`crate::error::Error`]. A route without this middleware still
49//! answers a validation failure with `422 application/problem+json`, so a JSON
50//! API and an Inertia frontend can share the same actions, the same validators
51//! and the same `ctx.request.validate::<T>()` call. Which rendering you get is
52//! decided by which route group you are in.
53
54use std::collections::BTreeMap;
55use std::path::PathBuf;
56use std::sync::{Arc, OnceLock};
57
58use serde::Serialize;
59use serde_json::{Map, Value, json};
60
61use crate::context::HttpContext;
62use crate::error::{Error, Result};
63use crate::http::Response;
64use crate::middleware::{BoxFuture, Middleware, Next};
65
66/// Session key holding the page a form was submitted from.
67const PREVIOUS_URL: &str = "__luxid_previous_url";
68
69/// Flash key holding validation errors for the next request.
70const ERRORS: &str = "errors";
71
72// ---------------------------------------------------------------------------
73// The per-request handle that lives on HttpContext
74// ---------------------------------------------------------------------------
75
76/// The request's Inertia state, set by the [`Inertia`] middleware.
77///
78/// Detached when the middleware did not run, in which case [`HttpContext::inertia`]
79/// fails with a message saying so rather than rendering something subtly wrong.
80#[derive(Debug, Clone, Default)]
81pub struct InertiaRequest {
82    inner: Option<Arc<RequestState>>,
83}
84
85#[derive(Debug)]
86struct RequestState {
87    /// True when the client sent `X-Inertia`, i.e. this is an XHR-style
88    /// navigation rather than a fresh browser load.
89    is_inertia: bool,
90    url: String,
91    version: Option<String>,
92    shared: Value,
93    shell: Arc<Shell>,
94    /// `X-Inertia-Partial-Data`, when it applies to the component being rendered.
95    only: Option<Vec<String>>,
96    except: Option<Vec<String>>,
97    partial_component: Option<String>,
98}
99
100impl InertiaRequest {
101    /// Whether the current request came from the Inertia client.
102    ///
103    /// Useful for the rare action that needs to behave differently on a fresh
104    /// page load, e.g. skipping an expensive prop the client already has.
105    pub fn is_inertia_request(&self) -> bool {
106        self.inner.as_ref().is_some_and(|state| state.is_inertia)
107    }
108
109    /// Whether the middleware ran on this route.
110    pub fn is_active(&self) -> bool {
111        self.inner.is_some()
112    }
113
114    fn state(&self) -> Result<&RequestState> {
115        self.inner.as_deref().ok_or_else(|| {
116            Error::internal(
117                "this route does not have Inertia enabled. Add \
118                 `.middleware((Auth::session(), Inertia::new(\"resources/js/app.jsx\")))` \
119                 to the route group.",
120            )
121        })
122    }
123}
124
125// ---------------------------------------------------------------------------
126// Rendering a page
127// ---------------------------------------------------------------------------
128
129impl HttpContext {
130    /// Render an Inertia page.
131    ///
132    /// ```ignore
133    /// async fn index(ctx: HttpContext) -> Result<Response> {
134    ///     let todos = Todo::owned_by(ctx.auth.id()?).paginate(1, 50).await?;
135    ///
136    ///     ctx.inertia("Todos/Index", json!({ "todos": todos }))
137    /// }
138    /// ```
139    ///
140    /// `component` is a path into the client's page directory —
141    /// `"Todos/Index"` resolves to `resources/js/Pages/Todos/Index.jsx`.
142    ///
143    /// The same call serves both a fresh browser load (an HTML shell) and an
144    /// Inertia navigation (JSON). The action does not know or care which.
145    ///
146    /// Consumes the context so any headers or cookies already set on
147    /// `ctx.response` are preserved.
148    pub fn inertia(self, component: &str, props: impl Serialize) -> Result<Response> {
149        let props = serde_json::to_value(props)
150            .map_err(|err| Error::internal(format!("inertia props for `{component}`: {err}")))?;
151
152        let state = self.inertia.state()?;
153        let response = self.response;
154
155        // Shared props first, so a page prop of the same name wins. That order
156        // is what lets one page override a globally shared value.
157        let mut merged = match state.shared.clone() {
158            Value::Object(map) => map,
159            _ => Map::new(),
160        };
161
162        if let Value::Object(map) = props {
163            merged.extend(map);
164        }
165
166        // Partial reloads: the client asks for a subset of the props it already
167        // knows the names of. Only honoured when the component matches — a
168        // partial request that lands on a different component is a full render,
169        // or the client would receive a page missing most of its data.
170        let component_matches = state
171            .partial_component
172            .as_deref()
173            .is_some_and(|name| name == component);
174
175        if component_matches {
176            if let Some(only) = &state.only {
177                merged.retain(|key, _| only.iter().any(|wanted| wanted == key));
178            }
179            if let Some(except) = &state.except {
180                merged.retain(|key, _| !except.iter().any(|unwanted| unwanted == key));
181            }
182        }
183
184        let mut page = json!({
185            "component": component,
186            "props": Value::Object(merged),
187            "url": state.url,
188        });
189
190        // The client compares this against its own copy and triggers a hard
191        // reload when they differ, which is how a deploy reaches open tabs.
192        if let Some(version) = &state.version {
193            page["version"] = json!(version);
194        }
195
196        if state.is_inertia {
197            return response
198                .header("x-inertia", "true")
199                // Without this, a cache can serve the JSON payload to a plain
200                // browser navigation, and the user gets a screenful of JSON.
201                .header("vary", "X-Inertia")
202                .json(page);
203        }
204
205        response.html(state.shell.render(&page))
206    }
207}
208
209// ---------------------------------------------------------------------------
210// The HTML shell
211// ---------------------------------------------------------------------------
212
213/// How the initial HTML document is produced on a fresh browser load.
214#[derive(Debug)]
215pub struct Shell {
216    title: String,
217    entry: String,
218    dev: bool,
219    dev_server: String,
220    manifest_path: PathBuf,
221    asset_base: String,
222    /// Parsed once. A production build's manifest does not change while the
223    /// process is running.
224    manifest: OnceLock<BTreeMap<String, ManifestEntry>>,
225}
226
227#[derive(Debug, Clone, serde::Deserialize)]
228struct ManifestEntry {
229    file: String,
230    #[serde(default)]
231    css: Vec<String>,
232}
233
234impl Shell {
235    fn render(&self, page: &Value) -> String {
236        let serialized = serde_json::to_string(page).unwrap_or_else(|_| "{}".to_owned());
237
238        format!(
239            "<!doctype html>\n\
240             <html lang=\"en\">\n\
241             <head>\n\
242             <meta charset=\"utf-8\">\n\
243             <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
244             <title>{title}</title>\n\
245             {tags}\n\
246             </head>\n\
247             <body>\n\
248             <div id=\"app\" data-page=\"{page}\"></div>\n\
249             </body>\n\
250             </html>\n",
251            title = escape_html(&self.title),
252            tags = self.tags(),
253            page = escape_html(&serialized),
254        )
255    }
256
257    /// The `<script>`/`<link>` tags that boot the client.
258    fn tags(&self) -> String {
259        if self.dev {
260            // Vite's dev server serves the entry and its HMR client directly.
261            // It sends permissive CORS headers, so loading these modules from
262            // another port is fine — this is the same arrangement Laravel's
263            // Vite plugin uses.
264            return format!(
265                "<script type=\"module\" src=\"{server}/@vite/client\"></script>\n\
266                 <script type=\"module\" src=\"{server}/{entry}\"></script>",
267                server = self.dev_server.trim_end_matches('/'),
268                entry = self.entry,
269            );
270        }
271
272        let manifest = self.manifest.get_or_init(|| {
273            std::fs::read_to_string(&self.manifest_path)
274                .ok()
275                .and_then(|raw| serde_json::from_str(&raw).ok())
276                .unwrap_or_default()
277        });
278
279        let Some(entry) = manifest.get(&self.entry) else {
280            // A missing manifest in a release build is a deployment mistake,
281            // and a blank page with no explanation is the worst way to find
282            // out. Say what is wrong, in the document itself.
283            return format!(
284                "<!-- luxid: no manifest entry for `{entry}` in `{path}`. \
285                 Run your frontend build, or set `.dev(true)`. -->",
286                entry = escape_html(&self.entry),
287                path = escape_html(&self.manifest_path.display().to_string()),
288            );
289        };
290
291        let base = self.asset_base.trim_end_matches('/');
292
293        let mut tags: Vec<String> = entry
294            .css
295            .iter()
296            .map(|href| format!("<link rel=\"stylesheet\" href=\"{base}/{href}\">"))
297            .collect();
298
299        tags.push(format!(
300            "<script type=\"module\" src=\"{base}/{file}\"></script>",
301            file = entry.file,
302        ));
303
304        tags.join("\n")
305    }
306}
307
308/// Escape text for an HTML attribute or text node.
309///
310/// `data-page` carries user-controlled JSON into an attribute, so this is a
311/// security boundary rather than a formatting nicety: without it, a todo
312/// titled `"><script>` would execute.
313fn escape_html(raw: &str) -> String {
314    let mut out = String::with_capacity(raw.len());
315
316    for ch in raw.chars() {
317        match ch {
318            '&' => out.push_str("&amp;"),
319            '<' => out.push_str("&lt;"),
320            '>' => out.push_str("&gt;"),
321            '"' => out.push_str("&quot;"),
322            '\'' => out.push_str("&#39;"),
323            _ => out.push(ch),
324        }
325    }
326
327    out
328}
329
330// ---------------------------------------------------------------------------
331// The middleware
332// ---------------------------------------------------------------------------
333
334type SharedProps = Arc<dyn Fn(&HttpContext) -> Result<Value> + Send + Sync>;
335
336/// Enables the Inertia protocol for a route group.
337///
338/// ```ignore
339/// r.group("/", |r| {
340///     r.middleware((Auth::session(), Inertia::new("resources/js/app.jsx")));
341///
342///     r.get("/", PagesController::home);
343/// });
344/// ```
345pub struct Inertia {
346    shell: Arc<Shell>,
347    version: Option<String>,
348    shared: Vec<SharedProps>,
349}
350
351impl Inertia {
352    /// `entry` is the client entry point as Vite names it in its manifest,
353    /// e.g. `"resources/js/app.jsx"`.
354    pub fn new(entry: impl Into<String>) -> Self {
355        Self {
356            shell: Arc::new(Shell {
357                title: "Luxid".to_owned(),
358                entry: entry.into(),
359                // Debug builds talk to the Vite dev server; release builds read
360                // the built manifest. Predictable, and overridable with `.dev`.
361                dev: cfg!(debug_assertions),
362                dev_server: "http://localhost:5173".to_owned(),
363                manifest_path: PathBuf::from("public/build/.vite/manifest.json"),
364                asset_base: "/build".to_owned(),
365                manifest: OnceLock::new(),
366            }),
367            version: None,
368            shared: Vec::new(),
369        }
370    }
371
372    fn shell_mut(&mut self) -> &mut Shell {
373        Arc::get_mut(&mut self.shell).expect("the shell is not shared during construction")
374    }
375
376    /// The `<title>` of the HTML shell. Client-side title changes are the
377    /// adapter's job; this is only the first paint.
378    pub fn title(mut self, title: impl Into<String>) -> Self {
379        self.shell_mut().title = title.into();
380        self
381    }
382
383    /// Serve assets from the Vite dev server (`true`) or a built manifest
384    /// (`false`). Defaults to `cfg!(debug_assertions)`.
385    pub fn dev(mut self, dev: bool) -> Self {
386        self.shell_mut().dev = dev;
387        self
388    }
389
390    pub fn dev_server(mut self, url: impl Into<String>) -> Self {
391        self.shell_mut().dev_server = url.into();
392        self
393    }
394
395    pub fn manifest(mut self, path: impl Into<PathBuf>) -> Self {
396        self.shell_mut().manifest_path = path.into();
397        self
398    }
399
400    /// URL prefix the built assets are served from. Must match the route the
401    /// application registers with `Router::static_files`.
402    pub fn asset_base(mut self, base: impl Into<String>) -> Self {
403        self.shell_mut().asset_base = base.into();
404        self
405    }
406
407    /// Asset version. When the client's copy differs, it hard-reloads instead
408    /// of navigating — which is how a deploy reaches tabs that are already open
409    /// and would otherwise keep requesting a bundle that no longer exists.
410    ///
411    /// A build hash or release tag is the usual value.
412    pub fn version(mut self, version: impl Into<String>) -> Self {
413        self.version = Some(version.into());
414        self
415    }
416
417    /// Props merged into every page rendered by this group.
418    ///
419    /// The authenticated user is the canonical example: every page wants it,
420    /// and no page should have to remember to include it.
421    ///
422    /// ```ignore
423    /// Inertia::new("resources/js/app.jsx")
424    ///     .share(|ctx| Ok(json!({ "auth": { "id": ctx.auth.try_identity().map(|i| i.subject()) } })))
425    /// ```
426    pub fn share(
427        mut self,
428        props: impl Fn(&HttpContext) -> Result<Value> + Send + Sync + 'static,
429    ) -> Self {
430        self.shared.push(Arc::new(props));
431        self
432    }
433}
434
435impl Middleware for Inertia {
436    fn handle<'a>(&'a self, mut ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>> {
437        Box::pin(async move {
438            let is_inertia = ctx.request.header("x-inertia").is_some();
439            let is_get = ctx.request.method().as_str() == "GET";
440            let url = full_path(&ctx);
441
442            // ---- asset version check --------------------------------------
443            //
444            // Only on GET. A stale version on a write would discard the user's
445            // input; Inertia's client handles that case itself.
446            if is_inertia && is_get {
447                let presented = ctx.request.header("x-inertia-version").unwrap_or("");
448                let current = self.version.as_deref().unwrap_or("");
449
450                if presented != current {
451                    // 409 tells the client to abandon the XHR and do a full
452                    // browser load of this location, picking up new assets.
453                    //
454                    // Built by hand rather than with `.no_content()`, which
455                    // would reset the status to 204.
456                    return Ok(Response::default()
457                        .status(409)
458                        .header("x-inertia-location", url));
459                }
460            }
461
462            // ---- shared props ---------------------------------------------
463            //
464            // Computed here, while the context still exists. Errors flashed by
465            // the *previous* request are read from the session and shared, which
466            // is what makes the redirect-back flow deliver them to the page.
467            let mut shared = Map::new();
468
469            let flashed_errors: Value = ctx
470                .session
471                .flashed(ERRORS)
472                .unwrap_or(None)
473                .unwrap_or_else(|| json!({}));
474
475            shared.insert(ERRORS.to_owned(), flashed_errors);
476
477            for provider in &self.shared {
478                if let Value::Object(map) = provider(&ctx)? {
479                    shared.extend(map);
480                }
481            }
482
483            // ---- remember where a form was submitted from -----------------
484            //
485            // Stored on GETs so a later POST knows where to bounce back to.
486            // Taken from the session rather than the `Referer` header, which is
487            // client-controlled and would make this an open redirect.
488            let session = ctx.session.clone();
489            let has_session = session.is_active();
490
491            if is_get && !is_inertia_partial(&ctx) && has_session {
492                let _ = session.put(PREVIOUS_URL, &url);
493            }
494
495            let back = session
496                .get::<String>(PREVIOUS_URL)
497                .unwrap_or(None)
498                .unwrap_or_else(|| "/".to_owned());
499
500            ctx.inertia = InertiaRequest {
501                inner: Some(Arc::new(RequestState {
502                    is_inertia,
503                    url,
504                    version: self.version.clone(),
505                    shared: Value::Object(shared),
506                    shell: self.shell.clone(),
507                    only: header_list(&ctx, "x-inertia-partial-data"),
508                    except: header_list(&ctx, "x-inertia-partial-except"),
509                    partial_component: ctx
510                        .request
511                        .header("x-inertia-partial-component")
512                        .map(str::to_owned),
513                })),
514            };
515
516            // ---- run the action -------------------------------------------
517            match next.run(ctx).await {
518                Ok(response) => Ok(response),
519
520                // The reason this middleware exists. A validation failure on an
521                // Inertia request is not an error document — it is a bounce back
522                // to the form with the errors attached.
523                Err(Error::Validation(errors)) if is_inertia => {
524                    if !has_session {
525                        return Err(Error::internal(
526                            "Inertia needs a session to report validation errors. Add \
527                             `Auth::session()` outside `Inertia::new(..)` on this group, \
528                             and bind a `SessionStore` in `providers()`.",
529                        ));
530                    }
531
532                    // Inertia's `errors` prop is one message per field; Luxid
533                    // collects every message. Taking the first matches what the
534                    // client adapters render and what every other server adapter
535                    // sends.
536                    let first: Map<String, Value> = errors
537                        .fields()
538                        .filter_map(|(field, messages)| {
539                            messages.first().map(|m| (field.clone(), json!(m)))
540                        })
541                        .collect();
542
543                    session.flash(ERRORS, Value::Object(first))?;
544
545                    // 303 rather than 302: after a PUT or DELETE, a 302 would
546                    // have the browser repeat the method against the new URL.
547                    Response::default().redirect(back)
548                }
549
550                Err(other) => Err(other),
551            }
552        })
553    }
554}
555
556/// Path plus query, which is what Inertia's `url` field expects.
557fn full_path(ctx: &HttpContext) -> String {
558    let uri = ctx.request.uri();
559
560    match uri.query() {
561        Some(query) => format!("{}?{}", uri.path(), query),
562        None => uri.path().to_owned(),
563    }
564}
565
566fn is_inertia_partial(ctx: &HttpContext) -> bool {
567    ctx.request.header("x-inertia-partial-component").is_some()
568}
569
570fn header_list(ctx: &HttpContext, name: &str) -> Option<Vec<String>> {
571    ctx.request.header(name).map(|raw| {
572        raw.split(',')
573            .map(str::trim)
574            .filter(|part| !part.is_empty())
575            .map(str::to_owned)
576            .collect()
577    })
578}