2024-01-21 17:33:53 +05:30
use cookie ::Cookie ;
2024-01-22 07:56:42 +05:30
/// Get a cookie by name, for both SSR and CSR
2024-01-21 17:41:14 +05:30
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_cookie)
///
/// ## Usage
///
/// This provides you with the cookie that has been set. For more details on how to use the cookie provided, refer: https://docs.rs/cookie/0.18/cookie/struct.Cookie.html
///
/// ```
/// # use leptos::*;
/// # use leptos_use::use_cookie;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
2024-01-23 15:39:52 +00:00
/// if let Some(cookie) = use_cookie("auth") {
/// view! {
/// <div>
/// format!("'auth' cookie set to `{}`", cookie.value())
/// </div>
/// }.into_view()
/// } else {
/// view! {
/// <div>
/// "No 'auth' cookie set"
/// </div>
/// }.into_view()
/// }
2024-01-21 17:41:14 +05:30
/// # }
/// ```
2024-01-23 15:39:52 +00:00
///
2024-01-23 15:44:33 +00:00
/// ## Server-Side Rendering
2024-01-23 15:39:52 +00:00
///
/// This works equally well on the server or the client.
/// On the server this function gets the cookie from the HTTP request header.
///
/// If you're using `axum` you have to enable the `"axum"` feature in your Cargo.toml.
/// In case it's `actix-web` enable the feature `"actix"`.
2024-01-21 17:41:14 +05:30
pub fn use_cookie ( cookie_name : & str ) -> Option < Cookie < 'static > > {
2024-01-21 17:33:53 +05:30
let cookies ;
#[ cfg(feature = " ssr " ) ]
{
use http ::HeaderValue ;
use leptos ::expect_context ;
let headers ;
2024-01-23 15:39:52 +00:00
#[ cfg(feature = " actix " ) ]
2024-01-21 17:33:53 +05:30
{
headers = expect_context ::< actix_web ::HttpRequest > ( ) . headers ( ) . clone ( ) ;
}
#[ cfg(feature = " axum " ) ]
{
2024-01-23 15:55:12 +00:00
headers = expect_context ::< http ::request ::Parts > ( ) . headers ;
2024-01-21 17:33:53 +05:30
}
cookies = headers
. get ( http ::header ::COOKIE )
. cloned ( )
. unwrap_or_else ( | | HeaderValue ::from_static ( " " ) )
. to_str ( )
. unwrap_or_default ( )
. to_owned ( ) ;
}
#[ cfg(not(feature = " ssr " )) ]
{
use wasm_bindgen ::JsCast ;
2024-01-21 17:41:14 +05:30
let js_value : wasm_bindgen ::JsValue = leptos ::document ( ) . into ( ) ;
2024-01-21 17:33:53 +05:30
let document : web_sys ::HtmlDocument = js_value . unchecked_into ( ) ;
cookies = document . cookie ( ) . unwrap_or_default ( ) ;
}
2024-01-21 17:41:14 +05:30
Cookie ::split_parse_encoded ( cookies )
2024-01-21 17:33:53 +05:30
. filter_map ( | cookie | cookie . ok ( ) )
. find ( | cookie | cookie . name ( ) = = cookie_name )
2024-01-21 17:41:14 +05:30
. map ( | cookie | cookie . into_owned ( ) )
2024-01-21 17:33:53 +05:30
}