aantron/dream

Tidy up the flash message cookies

Closed this issue · 0 comments

The Dream.flash_messages middleware currently always sets a dream.flash cookie — it's just empty if there are no flash messages. The same empty, unconditional dream.flash cookie is also used to effectively "delete" flash messages after they have been "received" by the next request, by overwriting them with the same empty message list.

This can be observed by running the w-flash example and looking in the network tab, where a dream.flash cookie will appear on the very first request — even though there are no flash messages set yet.

What should happen instead is:

  • If there were no flash messages, and none are added during a particular request, no cookie should be set.
  • If there were flash messages, and none are added during a request, the cookie should be deleted by setting ~expires:0. on the returned cookie.

The "lightly offending" code is here:

let flash_messages inner_handler request =
let outbox = ref [] in
let request = Dream.with_local storage outbox request in
let%lwt response = inner_handler request in
let entries = List.rev !outbox in
let content =
List.fold_right (fun (x,y) a -> `String x :: `String y :: a) entries [] in
let value = `List content |> Yojson.Basic.to_string in
Dream.set_cookie flash_cookie value request response ~max_age:five_minutes
|> Lwt.return