-
What is the intended way to pass context from server to client? Suppose that my web application needs to establish a WebSocket connection to some external url which should be configurable on server side. Ideally, I'd like to call Apparently this is not possible, so I am passing the context by a // main.rs
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
// ...
let app = Router::new()
.leptos_routes_with_context(
&leptos_options,
routes,
|| {
provide_context(MyContext::load_from_env());
},
App,
)
.fallback(leptos_axum::file_and_error_handler(|_| App))
.with_state(leptos_options);
// ...
} // app.rs
#[component]
pub fn App() -> impl IntoView {
let context = OnceResource::new(async { expect_context::<MyContext>() });
view! {
<!DOCTYPE html>
<html lang="en">
<body>
<Transition>
{move || {
context
.get()
.map(|ctx| {
provide_context(ctx);
view! { <ActualApp /> }
})
}}
</Transition>
</body>
</html>
}
}
#[component]
fn ActualApp() -> impl IntoView {
let context = expect_context::<MyContext>();
// ...
}
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Are you saying the above code works? I expect that to have issues during hydration and on subsequent page loads. Context is absolutely not designed to cross the server client boundary so that you don't leak information client shouldn't know. How this is usually done is with a server fn and a Resource, which explicitly sends data from the server to the client. We now have easy websockets support with those, see the 0.8 release notes and/or the server_fns example in the repo |
Beta Was this translation helpful? Give feedback.
-
If it literally doesn't need to be async, and it only needs to be done once, and can be done in the root of the application (in your example) so that it is available on every page, you can use |
Beta Was this translation helpful? Give feedback.
If it literally doesn't need to be async, and it only needs to be done once, and can be done in the root of the application (in your example) so that it is available on every page, you can use
SharedValue
, which is essentially a synchronousOnceResource
.