axum-flash
axum-flash copied to clipboard
Seeing inconsistent behaviour for different routes
Hi, I'm encountering odd behaviour when flashing messages for different routes in my Axum server and I'm not quite sure what the issue is.
For example, I have these routes for registering new users (under /register):
pub async fn get_register(flash: IncomingFlashes, Extension(tera): Extension<Tera>) -> Html<String> {
let mut context = tera::Context::new();
if flash.len() == 1{
context.insert("message", flash.iter().nth(0).unwrap().1);
}
Html(tera.render("register.html.tera", &context).unwrap())
}
pub async fn post_register(
form: Form<Register>,
mut flash: Flash,
DatabaseConnection(conn): DatabaseConnection,
) -> Redirect {
// Try to register the user
// [......]
Ok(_) => Redirect::to("/login"),
Err(e) => {
flash.error("Unable to register user");
Redirect::to("/register")
}
}
The flashing functionality works as expected for these routes (i.e. if there's an error during registration, the user is redirected and the flash message is shown. Upon refreshing the page, the flash message is cleared.
I then have some other routes (under /types/create) which are very similar to the above, but the flash message persists even after refreshing the page (and I can see the 'axum-flash' cookie stored in my browser after refreshing).
pub async fn get_create_type(flash: IncomingFlashes, Extension(tera): Extension<Tera>) -> Html<String>{
let mut context = tera::Context::new();
if flash.len() == 1{
context.insert("message", flash.iter().nth(0).unwrap().1);
}
Html(tera.render("new_type.html.tera", &context).unwrap())
}
pub async fn post_create_type(
form: Form<PostNewType>,
mut flash: Flash,
DatabaseConnection(conn): DatabaseConnection,
) -> Redirect {
// Logic to create a new type
// If a type with that name exists already, do:
flash.error("Type already exists");
Redirect::to("/types/create")
}
In these other routes, I've tried adding extra code to forcibly remove the 'axum-flash' cookie (I also tried using the other 2 types of CookieJar as well), but it still persists:
pub async fn get_create_type(flash: IncomingFlashes, jar: CookieJar, Extension(tera): Extension<Tera>) -> impl IntoResponse{
let mut context = tera::Context::new();
if flash.len() == 1{
context.insert("message", flash.iter().nth(0).unwrap().1);
}
// Attempt to remove the 'axum-flash' cookie
let updated_jar: CookieJar = jar.remove(Cookie::named("axum-flash"));
(updated_jar, Html(tera.render("new_type.html.tera", &context).unwrap()))
}
From this page (/types/create) with the persistent cookie, if I then navigate back to the /register route and refresh the page, the cookie is cleared.
Can you think of any reason why in some instances the flash cookie is cleared, but in other cases it's not? Let me know if you need more details on anything