Keep flash messages for another request

I’m working on a project that uses a strategy similar to Turbolinks and Pjax on the client, so all forms and links are sent to the server using AJAX requests.

HTTP redirects don’t work well with AJAX, so instead of a raw redirect the server responds with a “JSON encoded” redirect, and the client is responsible for visiting the url.

The problem I’m having with this approach is that flash messages are not kept between “fake” redirects. Is there a way to persist flash messages for another request? Or maybe there is a different approach I’m not seeing here.

Thanks!

2 Likes

Just as a side note, unpoly.js is very turbolinks-like, but newer, some more features, and handles redirects fine (you set a header). :slight_smile:

As for keeping the flash’es, that is handled by the :fetch_flash plug on your router, you can see its implementation at:

Basically if the status is 300.308 then it puts the flash back, else it deletes it, so if you could set the status that would work, or make your own replacement fetch_flash to detect some kind of assign or so, or PR in an option to persist a flash given some function or so, or a variety of other methods. :slight_smile:

Or if you can edit the front-end to look for a special header then do a redirect itself (like unpoly.js does) then that works too.

4 Likes

I didn’t know about unpoly. Thanks for the suggestion, I’ll look into it.

I’ll see if I can change the client to look for a header. Thanks

1 Like

Returning the status 303 did the trick for me. Phoenix keeps flash messages and the browser doesn’t automatically follow the redirect (as it does when it’s 302).

3 Likes

This is almost unbelievable, I’m doing exactly the same as OP and I’ve been stuck for a while, trying to find a solution.
This workaround seems to do the trick, thanks!