Is this the idiomatic way to initialize a session?

By “initialize” I mean add values so we can expect them everywhere. For example a user UUID (in my app users are temporary, they are not persisted).

From the router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :init_session         # <----- here
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers

  def init_session(conn, _opts) do
    case Plug.Conn.get_session(conn, "some_key") do
      nil -> put_session(conn, "some_key", "my value")
      _ -> conn

Of course I could call a custom plug module or other sophisticated initialization, but the real question is : do you just add a plug to set default values ?

In the rare cases where I needed it, yes, this is what I did.

1 Like