Search code examples
elixirphoenix-frameworkflash-message

Phoenix 1.3 flash not showing up


My put_flash(conn) and get_flash(conn) methods are behaving strangely; when I use redirect everything works fine, but nothing shows up when I try to add flash_msg in the controller behind.

Looks like the messages are stored in :phoenix_flash instead of :plug_session; any idea on what's wrong there?

  def index(conn, _params) do
    conn
    |> put_flash(:info, "Welcome : info")
    |> put_flash(:error, "Welcome : error")
    render conn, "index.html"
  end

private: %{EverlearnWeb.Router => {[], %{}}, 
:phoenix_action => :index,
:phoenix_controller => EverlearnWeb.PageController,
:phoenix_endpoint => EverlearnWeb.Endpoint,
:phoenix_flash => %{"error" => "Welcome : error", "info" => "Welcome : info"},
:phoenix_layout => {EverlearnWeb.LayoutView, :app},
:phoenix_pipelines => [:browser], :phoenix_router => EverlearnWeb.Router,
:phoenix_view => EverlearnWeb.PageView,
:plug_session => %{"_csrf_token" => "xxx",
 "phoenix_flash" => %{"info" => "Welcome back Thibaut, your are signed in !"},
 "user_id" => 1}, :plug_session_fetch => :done}

Solution

  • You need to pipe your conn that you put your flash messages into the render function:

    conn
    |> put_flash(:info, "Welcome : info")
    |> put_flash(:error, "Welcome : error")
    |> render("index.html")
    

    In your approach you added flash messages to a conn, but in render you are using non-updated one that has been passed to your action.

    Other approach would be to assign to a conn if you wish to pass the data correctly to render:

    conn =
      conn
      |> put_flash(:info, "Welcome : info")
      |> put_flash(:error, "Welcome : error")
    
    render conn, "index.html"