Installation
The session machinery is not included in the project scaffolded by pavex new.
You need to go through a few steps to set it up.
Dependencies
The core session logic lives in a standalone crate, pavex_session.
Support for different session storage backends is provided by separate crates, such as
pavex_session_sqlx and pavex_session_memory_store.
Choose a storage backend that fits your needs and then add the required dependencies to the Cargo.toml
of your application crate:
Blueprint
You need to add a few imports and middlewares to your Blueprint to get sessions up and running:
use pavex::{Blueprint, blueprint::from, cookie::INJECT_RESPONSE_COOKIES};
use pavex_session::FINALIZE_SESSION;
pub fn blueprint() -> Blueprint {
let mut bp = Blueprint::new();
bp.import(from![
// Other imports [..]
pavex, // (1)!
pavex_session, // (2)!
pavex_session_sqlx::postgres // (3)!
]);
bp.post_process(FINALIZE_SESSION); // (4)!
bp.post_process(INJECT_RESPONSE_COOKIES); // (5)!
// [...]
}
pavexprovides the core request/response types as well as cookies.pavex_sessionprovides theSessiontype and the machinery to manage the session lifecycle.pavex_session_sqlx::postgresprovides a Postgres-based session store implementation.finalize_sessionlooks at the current session state and decides whether a session cookie must be set or not on the outgoing response.inject_response_cookiesconvertsResponseCookiesintoSet-Cookieheaders on the response.
It must execute afterfinalize_session, otherwise the session cookie will not be set. If you get the order wrong, the code generation process will fail.
use pavex::{Blueprint, blueprint::from, cookie::INJECT_RESPONSE_COOKIES};
use pavex_session::FINALIZE_SESSION;
pub fn blueprint() -> Blueprint {
let mut bp = Blueprint::new();
bp.import(from![
// Other imports [..]
pavex, // (1)!
pavex_session, // (2)!
pavex_session_memory_store // (3)!
]);
bp.post_process(FINALIZE_SESSION); // (4)!
bp.post_process(INJECT_RESPONSE_COOKIES); // (5)!
// [...]
}
pavexprovides the core request/response types as well as cookies.pavex_sessionprovides theSessiontype and the machinery to manage the session lifecycle.pavex_session_memory_storeprovides the in-memory session store implementation.finalize_sessionlooks at the current session state and decides whether a session cookie must be set or not on the outgoing response.inject_response_cookiesconvertsResponseCookiesintoSet-Cookieheaders on the response.
It must execute afterfinalize_session, otherwise the session cookie will not be set. If you get the order wrong, the code generation process will fail.
Sessions are built on top of cookies, so both must be installed for sessions to work correctly.