Function leptos_use::use_cookie

source ·
pub fn use_cookie<T, C>(
    cookie_name: &str
) -> (Signal<Option<T>>, WriteSignal<Option<T>>)
where C: StringCodec<T> + Default + Clone, T: Clone,
Expand description

SSR-friendly and reactive cookie access.

You can use this function multiple times in your for the same cookie and they’re signals will synchronize (even across windows/tabs). But there is no way to listen to changes to document.cookie directly so in case something outside of this function changes the cookie, the signal will not be updated.

When the options max_age or expire is given then the returned signal will automatically turn to None after that time.

§Demo

Link to Demo

§Usage

The example below creates a cookie called counter. If the cookie doesn’t exist, it is initially set to a random value. Whenever we update the counter variable, the cookie will be updated accordingly.


let (counter, set_counter) = use_cookie::<u32, FromToStringCodec>("counter");

let reset = move || set_counter.set(Some(random()));

if counter.get().is_none() {
    reset();
}

let increase = move || {
    set_counter.set(counter.get().map(|c| c + 1));
};

view! {
    <p>Counter: {move || counter.get().map(|c| c.to_string()).unwrap_or("—".to_string())}</p>
    <button on:click=move |_| reset()>Reset</button>
    <button on:click=move |_| increase()>+</button>
}

See StringCodec for details on how to handle versioning — dealing with data that can outlast your code.

As part of the options when you use use_cookie_with_options you can specify cookie attributes.

let (cookie, set_cookie) = use_cookie_with_options::<bool, FromToStringCodec>(
    "user_info",
    UseCookieOptions::default()
        .max_age(3600_000) // one hour
        .same_site(SameSite::Lax)
);

§Server-Side Rendering

This works equally well on the server or the client. On the server this function reads the cookie from the HTTP request header and writes it back into the HTTP response header according to options (if provided). The returned WriteSignal will not affect the cookie headers on the server.

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", for spin enable "spin".

§Bring your own header

In case you’re neither using Axum nor Actix, or the default implementation is not to your liking, you can provide your own way of reading and writing the cookie header value.

use_cookie_with_options::<Auth, JsonCodec>(
    "auth",
    UseCookieOptions::default()
        .ssr_cookies_header_getter(|| {
            #[cfg(feature = "ssr")]
            {
                Some("Somehow get the value of the cookie header as a string".to_owned())
            }
        })
        .ssr_set_cookie(|cookie: &Cookie| {
            #[cfg(feature = "ssr")]
            {
                // somehow insert the Set-Cookie header for this cookie
            }
        }),
);

§Create Your Own Custom Codec

All you need to do is to implement the StringCodec trait together with Default and Clone.