How to delete a Phoenix Session?

8.2k views Asked by At

I'm going through the Phoenix Guide on Sessions. It explains it very well how I can bind data to a session using put_session and fetch the value later using get_session but it doesn't tell how I can delete a User's session.

From the guide:

defmodule HelloPhoenix.PageController do
  use Phoenix.Controller

  def index(conn, _params) do
    conn = put_session(conn, :message, "new stuff we just set in the session")
    message = get_session(conn, :message)

    text conn, message
  end
end
4

There are 4 answers

0
Sheharyar On BEST ANSWER

Found it in the Plug Docs:

clear_session(conn)

Clears the entire session.

This function removes every key from the session, clearing the session.

Note that, even if clear_session/1 is used, the session is still sent to the client. If the session should be effectively dropped, configure_session/2 should be used with the :drop option set to true.


You can put something like this in your SessionsController:

def delete(conn, _) do
  conn
  |> clear_session()
  |> redirect(to: page_path(conn, :index))
end

and add a route for this in your web/router.ex.

6
Paweł Obrok On

I think what you're looking for is configure_session:

Plug.Conn.configure_session(conn, drop: true)
0
DarckBlezzer On

Use only delete_session/2 to remove the session that you create before, and then redirect to login or something!

Example:

# In this example I use a log_out link to delete session when user click in it.
def log_out(conn, _params) do
    conn
    |> delete_session(:session_name)
    |> redirect(to: Routes.auth_path(conn, :login))
end

The important thing is return the conn modified, removing the key that you put in it.

0
Jeremie Ges On

If you want to delete a particular session you should use:

conn |> fetch_session |> delete_session(:session_to_delete)

More informations here:

https://github.com/elixir-lang/plug/blob/master/lib/plug/session.ex#L114:L115