Response cookies
Use ResponseCookies::insert to attach cookies to the response.
The inject_response_cookies middleware will take care of adding a Set-Cookie
header to the response for each cookie stored inside ResponseCookies.
Add a response cookie
Inject &mut ResponseCookies into the component that needs to set a cookie:
use pavex::Response;
use pavex::cookie::{ResponseCookie, ResponseCookies};
use pavex::get;
use pavex::time::Zoned;
#[get(path = "/")]
pub fn insert_cookie(response_cookies: &mut ResponseCookies) -> Response {
let now = Zoned::now().to_string();
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 routes, 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::Response;
use pavex::cookie::{RemovalCookie, ResponseCookies};
use pavex::get;
#[get(path = "/")]
pub fn delete_cookie(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.