I currently have the code below in a controller helper module. It allows me to redirect back to the previous page by grabbing the the conn's referrer. The problem with this is if there is a invalid input on a form for example, the conn's referrer is reset to the current page.
def redirect_back(conn, alternative \\ "/") do
path = conn
|> get_req_header("referer")
|> referrer
path || alternative
end
defp referrer([]), do: nil
defp referrer([h|_]), do: h
How can I hold the referrer to the correct previous page so I can use it to redirect even if something like an invalid input occurs?
There was a discussion in phoenix issues on the topic, that resulted in the fancy small library that you might want to include into your project and use like this:
def redirect_back(conn, alternative \\ "/") do
conn |> NavigationHistory.last_path(default: alternative)
end
or in any other way, described in it’s README/help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With