use_cookie
SSR-friendly and reactive cookie access.
You can use this function multiple times for the same cookie and their 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
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.
use leptos::prelude::*;
use leptos_use::use_cookie;
use codee::string::FromToStringCodec;
use rand::prelude::*;
#[component]
fn Demo() -> impl IntoView {
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>
}
}
Values are (en)decoded via the given codec. You can use any of the string codecs or a
binary codec wrapped in Base64
.
Please check the codec chapter to see what codecs are available and what feature flags they require.
Cookie attributes
As part of the options when you use use_cookie_with_options
you can specify cookie attributes.
use cookie::SameSite;
use leptos::prelude::*;
use leptos_use::{use_cookie_with_options, UseCookieOptions};
use codee::string::FromToStringCodec;
#[component]
fn Demo() -> impl IntoView {
let (cookie, set_cookie) = use_cookie_with_options::<bool, FromToStringCodec>(
"user_info",
UseCookieOptions::default()
.max_age(3600_000) // one hour
.same_site(SameSite::Lax)
);
view! {}
}
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
may not affect the cookie headers on the server! It will try and write
the headers buy if this happens after the headers have already been streamed to the client then
this will have no effect.
If you're using
axum
you have to enable the"axum"
feature in your Cargo.toml. In case it'sactix-web
enable the feature"actix"
, forspin
enable"spin"
.
Bring your own header
In case you're neither using Axum, Actix nor Spin, 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::Cookie;
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use leptos_use::{use_cookie_with_options, UseCookieOptions};
use codee::string::JsonSerdeCodec;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Auth {
pub username: String,
pub token: String,
}
#[component]
fn Demo() -> impl IntoView {
use_cookie_with_options::<Auth, JsonSerdeCodec>(
"auth",
UseCookieOptions::default()
.ssr_cookies_header_getter(|| {
#[cfg(feature = "ssr")]
{
Some("Somehow get the value of the cookie header as a string".to_owned())
}
#[cfg(not(feature = "ssr"))]
None
})
.ssr_set_cookie(|cookie: &Cookie| {
#[cfg(feature = "ssr")]
{
// somehow insert the Set-Cookie header for this cookie
}
}),
);
view! {}
}
Feature
This function is only available if the crate feature
use_cookie
is enabled