Expand description
An HTTP Cookie crate.
§Overview
Exposes types like Cookie and CookieJar for working with HTTP cookies. This crate
focuses on server side applications. The main goals are simplicity and ease of use.
§Prefix cookies
Cookie::host and Cookie::secure build cookies that use the __Host- and __Secure-
name prefixes (RFC 6265bis §4.1.3).
They set the attributes the prefix requires as defaults (which you may override) and apply
the prefix to the name on serialization. Parsing strips a recognized prefix from the name, so
a prefixed cookie is looked up in a CookieJar by its logical (unprefixed) name.
use cookie_monster::Cookie;
let cookie = Cookie::host("id", "abc").build();
assert_eq!(cookie.serialize().as_deref(), Ok("__Host-id=abc; Path=/; Secure"));§Usage
Add cookie-monster in your Cargo.toml:
[dependencies]
cookie-monster = "0.1"§Features
-
jiffAdds support for the jiff crate. This exposes methods to
Cookieto retrieve theExpiresandMax-Ageattributes with jiff specific types. -
chronoAdds support for the chrono crate. This exposes methods to
Cookieto retrieve theExpiresandMax-Ageattributes with chrono specific types. -
timeAdds support for the time crate. This exposes methods to
Cookieto retrieve theExpiresandMax-Ageattributes with time specific types. -
percent-encodeParse/serialize
Cookies that are percent-encoded. -
axumAdds integration with the axum crate.
ImplementsIntoResponseandIntoResponsePartsforCookieandCookieJar.
ImplementsFromRequestPartsonly forCookieJar -
httpAdds integration with the http crate. Create a
CookieJarfrom aHeaderMap. Write aCookieJarto aHeaderMap.
§Axum example
use axum::response::IntoResponse;
use cookie_monster::{Cookie, CookieJar, SameSite};
static COOKIE_NAME: &str = "session";
async fn handler(mut jar: CookieJar) -> impl IntoResponse {
if let Some(cookie) = jar.get(COOKIE_NAME) {
// Remove cookie
println!("Removing cookie {cookie:?}");
jar.remove(Cookie::named(COOKIE_NAME));
} else {
// Set cookie.
let cookie = Cookie::build(COOKIE_NAME, "hello, world")
.http_only()
.same_site(SameSite::Strict);
println!("Setting cookie {cookie:?}");
jar.add(cookie);
}
// Return the jar so the cookies are updated
jar
}§Honorable mention
This crate takes a lot of inspiration from the cookie crate.
Structs§
- Cookie
- An HTTP Cookie.
- Cookie
Builder - A builder struct for building a
Cookie. - Cookie
Jar - A generic
CookieJarfor cookie management. Can be used to read update or delete cookies from a user session.