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_cookie::use_cookie;
use codee::string::FromToStringCodec;
use rand::random;
#[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_cookie::{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
Make sure you follow the instructions in 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 but if this happens after the headers have already been streamed to the client then
this will have no effect.
If you’re using
axumyou have to enable the"axum"feature in your Cargo.toml. In case it’sactix-webenable the feature"actix"..
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::Cookie;
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use leptos_use_cookie::{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! {}
}
Installation
cargo add leptos-use-cookie
Options
UseCookieOptions
Options for use_cookie_with_options.
Every option is set with a builder method of the same name, e.g. UseCookieOptions::default().max_age(...). See also the API docs.
max_age
Type: Option<i64>
Max-Age of the cookie in milliseconds. The returned signal will turn to None after the max age is reached.
Default: None
The cookie storage model specification states that if both
expiresandmax_ageis set, thenmax_agetakes precedence, but not all clients may obey this, so if both are set, they should point to the same date and time!
If neither of
expiresandmax_ageis set, the cookie will be session-only and removed when the user closes their browser.
expires
Type: Option<i64>
Expiration date-time of the cookie as UNIX timestamp in seconds.
The signal will turn to None after the expiration date-time is reached.
Default: None
The cookie storage model specification states that if both
expiresandmax_ageis set, thenmax_agetakes precedence, but not all clients may obey this, so if both are set, they should point to the same date and time!
If neither of
expiresandmax_ageis set, the cookie will be session-only and removed when the user closes their browser.
http_only
Type: bool
Specifies the HttpOnly cookie attribute.
When true, the HttpOnly attribute is set; otherwise it is not.
By default, the HttpOnly attribute is not set.
Be careful when setting this to
true, as compliant clients will not allow client-side JavaScript to see the cookie indocument.cookie.
secure
Type: bool
Specifies the value for the Secure cookie attribute.
When true, the Secure attribute is set; otherwise it is not.
By default, the Secure attribute is not set.
Be careful when setting this to
true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. This can lead to hydration errors.
domain
Type: Option<String>
Specifies the value for the Domain cookie attribute.
By default, no domain is set, and most clients will consider applying the cookie only to the current domain.
path
Type: Option<String>
Specifies the value for the Path cookie attribute.
By default, the path is considered the “default path”.
same_site
Type: Option<SameSite>
Specifies the value for the SameSite cookie attribute.
'Some(SameSite::Lax)'will set theSameSiteattribute toLaxfor lax same-site enforcement.'Some(SameSite::None)'will set theSameSiteattribute toNonefor an explicit cross-site cookie.'Some(SameSite::Strict)'will set theSameSiteattribute toStrictfor strict same-site enforcement.Nonewill not set theSameSiteattribute (default).
More information about the different enforcement levels can be found in the specification.
default_value
Type: Option<T>
The default cookie value in case the cookie is not set.
Defaults to None.
readonly
Type: bool
If true the returned WriteSignal will not affect the actual cookie.
Default: false
ssr_cookies_header_getter
Type: Arc<dyn Fn() -> Option<String> + Send + Sync>
Getter function to return the string value of the cookie header.
When you use one of the features "axum" or "actix" there’s a valid default implementation provided.
ssr_set_cookie
Type: Arc<dyn Fn(&Cookie) + Send + Sync>
Function to add a set cookie header to the response on the server.
When you use one of the features "axum" or "actix" there’s a valid default implementation provided.
on_error
Type: Arc<dyn Fn(CodecError<E, D>) + Send + Sync>
Callback for encoding/decoding errors. Defaults to logging the error to the console.