How to delete cookies in case they exist?

I've been trying to find a way to delete some cookies, in case they do exist, when making a POST request to the /logout route in my actix-web server. An example of which they wouldn't be there is if the user deleted them under the application tab (probably to play around with stuff):

pub async fn logout_post(req: HttpRequest, session: Session) -> impl Responder {
    let settings = settings::get_settings();
    let mut response = HttpResponse::Ok();

    if let Some(mut auth_cookie) = req.cookie(settings.auth_cookie_name.as_str()) {
        auth_cookie.make_removal();
        response = response.cookie(auth_cookie);
    }

    if let Some(mut csrf_cookie) = req.cookie("csrf") {
        csrf_cookie.make_removal();
        response = response.cookie(csrf_cookie);
    }

    session.purge();

    response.json(json!({ "redirect": "/" }))
}

However, I found this error message when adding the cookie to the response using the cookie function:

mismatched types
expected `HttpResponseBuilder`, found `&mut HttpResponseBuilder`

I tried using the mutable Response type from the http crate, but the problem is that it doesn't have the trait Responder. In retrospect, it also wouldn't be the most appropriate given the potential for conflicts with my other crates, which rely on actix associated crates (eg. actix-http, actix-session).

If I can't solve this issue directly, are there other possible workarounds, such as making users unable to delete a specific cookie?

That’s a builder type, which uses the (&mut self, args…) -> &mut Self API-pattern for convenience so you’re allowed to ignore the return value (as it’s doing in-place mutation of the builder), but also able to chain method calls.

Just remove those response = prefixes.

    if let Some(mut auth_cookie) = req.cookie(settings.auth_cookie_name.as_str()) {
        auth_cookie.make_removal();
        response.cookie(auth_cookie);
    }

    if let Some(mut csrf_cookie) = req.cookie("csrf") {
        csrf_cookie.make_removal();
        response.cookie(csrf_cookie);
    }
1 Like

I've never found API-patterns in documentations useful, but this makes me look at them much differently.