Session
Quokka comes with an extensible Session type. It can be extracted using an Extension and be returned in a response as it implements the
IntoResponseParts trait. When present in a response, the session layer will automatically save the updated session.
Using a session
Here we get a simple session handler which increments a counter as soon as the user hits the route
#[derive(Default, serde::Deserialize, serde::Serialize)]
struct SessionCounter {
counter: u32,
}
#[axum::debug_handler]
async fn write_session(mut sess: Extension<Session>) -> impl IntoResponse {
let counter = sess.get_extension::<SessionCounter>("counter").unwrap_or_default();
counter.counter += 1;
let response = format!("You visited the page {} times", counter.counter);
sess.add_extension("counter", counter).expect("Write the updated counter back to the session");
(sess, response)
}
This will increment the counter as soon as the user refreshes the page and displays the visit count to the user. The session will be stored to the database when it gets returned by the handler.