Some data belongs on every page: the application's name, the signed-in user. In this chapter we'll look at the two places this crate lets you share a prop, when each one runs, and how the page reports which of its props were shared.
This chapter assumes Chapter 1. It does not cover lazy or deferred shared props.
Two places to share
The props! macro wrote down app_name exactly as it was spelled, the way a court reporter would. It had no opinion about JavaScript. The layout asked the page for appName, got undefined, and rendered a title bar with nothing in it.
Sometimes it can become a hassle to pass the same value from every handler. Thankfully, there are two hooks, one for the application and one for the request. Take a look at Example 2-1.
Example 2-1. Sharing for the application and for the request
pub fn config() -> Config {
Config::new()
.version("1")
.share(|_request| props! { app_name => "Ledger" })
}
pub async fn share_user(inertia: Inertia, request: Request, next: Next) -> Response {
inertia.share("auth", props! { user => "Mary" });
next.run(request).await
}
Let's walk through the two. Config::share takes a callback and runs it on every render, so it suits values that don't depend on who is asking. Inertia::share is called on the per-request handle, here from an Axum middleware, so it suits the current user.¹
Example 2-2 is the page those two produce, together with the struct from Chapter 1.
Example 2-2. The page object
{"component":"Invoices/Show",
"props":{"errors":{},"app_name":"Ledger","auth":{"user":"Mary"},
"invoiceId":7,"totalCents":1200,"paidAt":null},
"url":"/invoices/7","version":"1",
"sharedProps":["errors","app_name","auth"]}
As you can see, the key is app_name. The macro uses a name as written, and nothing converts it. The struct's keys are camelCase only because the struct asked serde for that.
The last field, sharedProps, lists the top-level keys that were shared. It is on by default, and Config::expose_shared_prop_keys(false) turns it off.
What this chapter leaves open
So one page now carries app_name beside invoiceId, and both are correct. Which convention do you want your React code to read? If it is camelCase, do you write "appName" => ... in every props! block by hand, or share a struct that carries the rename? Which of those will the next handler's author find on their own?
Testing
Example 2-3 fails if either hook stops running.
Example 2-3. Asserting shared props
page.equals("app_name", "Ledger").equals("auth.user", "Mary");
TL;DR
Config::share runs a callback on every render and is the place for application-wide props. Inertia::share adds a prop for one request and is usually called from a middleware. Keys written in props! are used as written. The page's sharedProps field lists the shared top-level keys unless you turn it off.
¹ The extractor works in middleware because InertiaLayer puts the handle in the request's extensions, and the layer is added after the middleware, so it wraps it.