Response cookies
To attach cookies to the response, you need to insert them into ResponseCookies
.
The response_cookie_injector
middleware in CookieKit
will take care of adding a Set-Cookie
header to the response for each cookie inside ResponseCookies
.
Add a response cookie
Inject &mut ResponseCookies
into the component that needs to set a cookie:
use pavex::cookie::{ResponseCookie, ResponseCookies};
use pavex::response::Response;
use pavex::time::{format_description::well_known::Iso8601, OffsetDateTime};
pub fn handler(response_cookies: &mut ResponseCookies) -> Response {
let now = OffsetDateTime::now_utc().format(&Iso8601::DEFAULT).unwrap();
let cookie = ResponseCookie::new("last_visited", now)
// We restrict the cookie to a specific path.
.set_path("/web");
// Make sure to insert the cookie into `&mut ResponseCookies`!
// Otherwise, the cookie won't be attached to the response.
response_cookies.insert(cookie);
// You don't have to manually attach the cookie to the response!
// It'll be done by the injector middleware at the end of the request
// processing pipeline.
Response::ok()
}
You can use ResponseCookie::new
to start building a new cookie.
It exposes multiple set_*
methods to configure the cookie's properties: Path
, Domain
, Secure
, HttpOnly
, etc.
Note
You can only inject mutable references into request handlers, pre-processing middlewares, and post-processing middlewares. As a result, you can only set cookies in those components. Check out "No mutations" for more information on the rationale.
Remove a client-side cookie
If you want to tell the client to delete a cookie, you need to insert a RemovalCookie
into ResponseCookies
:
use pavex::cookie::{RemovalCookie, ResponseCookies};
use pavex::response::Response;
pub fn handler(response_cookies: &mut ResponseCookies) -> Response {
let cookie = RemovalCookie::new("last_visited")
// We need to match the path of the cookie we want to delete.
.set_path("/web");
response_cookies.insert(cookie);
Response::ok()
}
The client will receive a Set-Cookie
header with the cookie name and an empty value,
along with an expiration date in the past.
You need to make sure that the Path
and Domain
properties on the RemovalCookie
match the ones
set on the client-side cookie you want to delete.