Struct DioxusServerContext

Source
pub struct DioxusServerContext { /* private fields */ }
Available on crate feature server only.
Expand description

A shared context for server functions that contains information about the request and middleware state.

You should not construct this directly inside components or server functions. Instead use server_context() to get the server context from the current request.

§Example

#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    let server_context = server_context();
    let headers: http::HeaderMap = server_context.extract().await?;
    println!("{:?}", headers);
    Ok(())
}

Implementations§

Source§

impl DioxusServerContext

Source

pub fn new(parts: Parts) -> Self

Create a new server context from a request

Source

pub fn get<T: Any + Send + Sync + Clone + 'static>(&self) -> Option<T>

Clone a value from the shared server context. If you are using DioxusRouterExt, any values you insert into the launch context will also be available in the server context.

Example:

use dioxus::prelude::*;

LaunchBuilder::new()
    // You can provide context to your whole app (including server functions) with the `with_context` method on the launch builder
    .with_context(server_only! {
        1234567890u32
    })
    .launch(app);

#[server]
async fn read_context() -> Result<u32, ServerFnError> {
    // You can extract values from the server context with the `extract` function
    let FromContext(value) = extract().await?;
    Ok(value)
}

fn app() -> Element {
    let future = use_resource(read_context);
    rsx! {
        h1 { "{future:?}" }
    }
}
Source

pub fn insert<T: Any + Send + Sync + 'static>(&self, value: T)

Insert a value into the shared server context

Source

pub fn insert_any(&self, value: Box<dyn Any + Send + Sync + 'static>)

Insert a boxed Any value into the shared server context

Source

pub fn insert_factory<F, T>(&self, value: F)
where F: Fn() -> T + Send + Sync + 'static, T: 'static,

Insert a factory that creates a non-sync value for the shared server context

Source

pub fn insert_boxed_factory( &self, value: Box<dyn Fn() -> Box<dyn Any> + Send + Sync>, )

Insert a boxed factory that creates a non-sync value for the shared server context

Source

pub fn response_parts(&self) -> RwLockReadGuard<'_, Parts>

Get the response parts from the server context

This method interacts with information from the current request. The request may come from:

  1. The initial SSR render if this method called from a Component or a server function that is called during the initial render
#[component]
fn PrintHtmlRequestInfo() -> Element {
    // The server context only exists on the server, so we need to put it behind a server_only! config
    server_only! {
        // Since we are calling this from a component, the server context that is returned will be from
        // the html request for ssr rendering
        let context = server_context();
        let request_parts = context.request_parts();
        println!("headers are {:?}", request_parts.headers);
    }
    rsx! {}
}
  1. A request to a server function called directly from the client (either on desktop/mobile or on the web frontend after the initial render)
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    // Since we are calling this from a server function, the server context that is may be from the
    // initial request or a request from the client
    let context = server_context();
    let request_parts = context.request_parts();
    println!("headers are {:?}", request_parts.headers);
    Ok(())
}

#[component]
fn CallServerFunction() -> Element {
    rsx! {
        button {
            // If you click the button, the server function will be called and the server context will be
            // from the client request
            onclick: move |_| async {
                _ = read_headers().await
            },
            "Call server function"
        }
    }
}
§Example
#[server]
async fn set_headers() -> Result<(), ServerFnError> {
    let server_context = server_context();
    let response_parts = server_context.response_parts();
    let cookies = response_parts
        .headers
        .get("Cookie")
        .ok_or_else(|| ServerFnError::new("failed to find Cookie header in the response"))?;
    println!("{:?}", cookies);
    Ok(())
}
Source

pub fn response_parts_mut(&self) -> RwLockWriteGuard<'_, Parts>

Get the response parts from the server context

This method interacts with information from the current request. The request may come from:

  1. The initial SSR render if this method called from a Component or a server function that is called during the initial render
#[component]
fn PrintHtmlRequestInfo() -> Element {
    // The server context only exists on the server, so we need to put it behind a server_only! config
    server_only! {
        // Since we are calling this from a component, the server context that is returned will be from
        // the html request for ssr rendering
        let context = server_context();
        let request_parts = context.request_parts();
        println!("headers are {:?}", request_parts.headers);
    }
    rsx! {}
}
  1. A request to a server function called directly from the client (either on desktop/mobile or on the web frontend after the initial render)
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    // Since we are calling this from a server function, the server context that is may be from the
    // initial request or a request from the client
    let context = server_context();
    let request_parts = context.request_parts();
    println!("headers are {:?}", request_parts.headers);
    Ok(())
}

#[component]
fn CallServerFunction() -> Element {
    rsx! {
        button {
            // If you click the button, the server function will be called and the server context will be
            // from the client request
            onclick: move |_| async {
                _ = read_headers().await
            },
            "Call server function"
        }
    }
}
§Example
#[server]
async fn set_headers() -> Result<(), ServerFnError> {
    let server_context = server_context();
    server_context.response_parts_mut()
        .headers
        .insert("Cookie", http::HeaderValue::from_static("dioxus=fullstack"));
    Ok(())
}
Source

pub fn request_parts(&self) -> RwLockReadGuard<'_, Parts>

Get the request parts

This method interacts with information from the current request. The request may come from:

  1. The initial SSR render if this method called from a Component or a server function that is called during the initial render
#[component]
fn PrintHtmlRequestInfo() -> Element {
    // The server context only exists on the server, so we need to put it behind a server_only! config
    server_only! {
        // Since we are calling this from a component, the server context that is returned will be from
        // the html request for ssr rendering
        let context = server_context();
        let request_parts = context.request_parts();
        println!("headers are {:?}", request_parts.headers);
    }
    rsx! {}
}
  1. A request to a server function called directly from the client (either on desktop/mobile or on the web frontend after the initial render)
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    // Since we are calling this from a server function, the server context that is may be from the
    // initial request or a request from the client
    let context = server_context();
    let request_parts = context.request_parts();
    println!("headers are {:?}", request_parts.headers);
    Ok(())
}

#[component]
fn CallServerFunction() -> Element {
    rsx! {
        button {
            // If you click the button, the server function will be called and the server context will be
            // from the client request
            onclick: move |_| async {
                _ = read_headers().await
            },
            "Call server function"
        }
    }
}
§Example
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    let server_context = server_context();
    let request_parts = server_context.request_parts();
    let id: &i32 = request_parts
        .extensions
        .get()
        .ok_or_else(|| ServerFnError::new("failed to find i32 extension in the request"))?;
    println!("{:?}", id);
    Ok(())
}
Source

pub fn request_parts_mut(&self) -> RwLockWriteGuard<'_, Parts>

Get the request parts mutably

This method interacts with information from the current request. The request may come from:

  1. The initial SSR render if this method called from a Component or a server function that is called during the initial render
#[component]
fn PrintHtmlRequestInfo() -> Element {
    // The server context only exists on the server, so we need to put it behind a server_only! config
    server_only! {
        // Since we are calling this from a component, the server context that is returned will be from
        // the html request for ssr rendering
        let context = server_context();
        let request_parts = context.request_parts();
        println!("headers are {:?}", request_parts.headers);
    }
    rsx! {}
}
  1. A request to a server function called directly from the client (either on desktop/mobile or on the web frontend after the initial render)
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    // Since we are calling this from a server function, the server context that is may be from the
    // initial request or a request from the client
    let context = server_context();
    let request_parts = context.request_parts();
    println!("headers are {:?}", request_parts.headers);
    Ok(())
}

#[component]
fn CallServerFunction() -> Element {
    rsx! {
        button {
            // If you click the button, the server function will be called and the server context will be
            // from the client request
            onclick: move |_| async {
                _ = read_headers().await
            },
            "Call server function"
        }
    }
}
§Example
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    let server_context = server_context();
    let id: i32 = server_context.request_parts_mut()
        .extensions
        .remove()
        .ok_or_else(|| ServerFnError::new("failed to find i32 extension in the request"))?;
    println!("{:?}", id);
    Ok(())
}
Source

pub async fn extract<M, T: FromServerContext<M>>( &self, ) -> Result<T, T::Rejection>

Extract part of the request.

This method interacts with information from the current request. The request may come from:

  1. The initial SSR render if this method called from a Component or a server function that is called during the initial render
#[component]
fn PrintHtmlRequestInfo() -> Element {
    // The server context only exists on the server, so we need to put it behind a server_only! config
    server_only! {
        // Since we are calling this from a component, the server context that is returned will be from
        // the html request for ssr rendering
        let context = server_context();
        let request_parts = context.request_parts();
        println!("headers are {:?}", request_parts.headers);
    }
    rsx! {}
}
  1. A request to a server function called directly from the client (either on desktop/mobile or on the web frontend after the initial render)
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    // Since we are calling this from a server function, the server context that is may be from the
    // initial request or a request from the client
    let context = server_context();
    let request_parts = context.request_parts();
    println!("headers are {:?}", request_parts.headers);
    Ok(())
}

#[component]
fn CallServerFunction() -> Element {
    rsx! {
        button {
            // If you click the button, the server function will be called and the server context will be
            // from the client request
            onclick: move |_| async {
                _ = read_headers().await
            },
            "Call server function"
        }
    }
}
§Example
#[server]
async fn read_headers() -> Result<(), ServerFnError> {
    let server_context = server_context();
    let headers: http::HeaderMap = server_context.extract().await?;
    println!("{:?}", headers);
    Ok(())
}

Trait Implementations§

Source§

impl Clone for DioxusServerContext

Source§

fn clone(&self) -> DioxusServerContext

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for DioxusServerContext

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> MaybeSendSync for T