Search code examples
elixirphoenix-framework

Elixir + Phoenix: delete_resp_cookie does not do anything


I have a /logout endpoint that. I want to delete my x-auth-token cookie in that controller action but it isn't doing anything when I check the front end (a react / remix app)

I read the docs and am providing the same options to delete_resp_cookie as I did for put_resp_cookie: https://hexdocs.pm/plug/Plug.Conn.html#delete_resp_cookie/3

  def login_callback(conn, %{"code" => code}) do
    ...

    one_week = 7 * 24 * 60 * 60

    conn
    |> put_resp_cookie("x-auth-token", %{job_seeker_id: generated_user.id},
      path: "/",
      max_age: one_week,
      http_only: true,
      secure: true,
      same_site: "strict",
      domain: Application.get_env(:myapp, :client_domain),
      sign: true
    )
    |> redirect(external: "#{Application.get_env(:myapp, :client_url)}/login_success")
  end

  def logout(conn, _params) do
    one_week = 7 * 24 * 60 * 60

    conn
    |> delete_resp_cookie("x-auth-token",
      path: "/",
      max_age: one_week,
      http_only: true,
      secure: true,
      same_site: "strict",
      domain: Application.get_env(:myapp, :client_domain),
      sign: true
    )
    |> json(%{success: true})
  end

However, after I make the request and check my frontend, the cookie is still there. Do I need to do anything else?


Solution

  • Plug.Conn.delete_resp_cookie sends a header updating the cookie's max_age and the browser is responsible for actually expiring that data.

    Setting the max_age of a cookie to 0 is a common way to delete a cookie. When the browser receives a cookie with max_age=0, it will typically delete the cookie immediately. This is setting the cookie's expiration date to a past date (1970), instructing the browser to discard it.

    Additionally you should make sure that your frontend javascript is not memoizing or caching the original cookie in some way. (I notice you trigger a redirect on login but not for logout, which may also be playing some role.)