Nex.Session (nex_core v0.4.3)

Copy Markdown

Session-scoped state management — persists across page navigations for the same browser session.

Unlike Nex.Store (which is page-scoped and cleared on refresh), session state survives page navigations and is tied to a session cookie (_nex_session).

Usage

# In mount/1 — read session state
def mount(_params) do
  user_id = Nex.Session.get(:user_id)
  %{logged_in: user_id != nil, user_id: user_id}
end

# In an action — write session state
def login(req) do
  email = req.body["email"]
  password = req.body["password"]

  case authenticate(email, password) do
    {:ok, user} ->
      Nex.Session.put(:user_id, user.id)
      {:redirect, "/dashboard"}

    {:error, _} ->
      Nex.Flash.put(:error, "Invalid credentials")
      {:redirect, "/login"}
  end
end

def logout(_req) do
  Nex.Session.clear()
  {:redirect, "/"}
end

How it works

Session data is stored in Nex.Store (ETS) keyed by a session ID. The session ID is stored in a signed cookie (_nex_session) using Phoenix.Token. This is stateful server-side session storage — no data is stored in the cookie itself.

TTL

Session data expires after 7 days of inactivity (configurable via :nex_core, :session_ttl).

Summary

Functions

Clears all data from the current session and deletes the session cookie.

Clears session state from the process dictionary. Called after response is sent.

Deletes a key from the current session.

Gets a value from the current session.

Loads the session from the cookie. Called by Nex.Handler at request start.

Persists the session cookie if a session was created or modified. Called by Nex.Handler before sending the response.

Puts a value into the current session.

Returns the current session ID, or nil if no session exists.

Updates a value in the current session using a function.

Functions

clear()

Clears all data from the current session and deletes the session cookie.

clear_process_state()

Clears session state from the process dictionary. Called after response is sent.

delete(key)

Deletes a key from the current session.

get(key, default \\ nil)

Gets a value from the current session.

load_from_conn(conn)

Loads the session from the cookie. Called by Nex.Handler at request start.

persist_to_conn(conn)

Persists the session cookie if a session was created or modified. Called by Nex.Handler before sending the response.

put(key, value)

Puts a value into the current session.

session_id()

Returns the current session ID, or nil if no session exists.

update(key, default, fun)

Updates a value in the current session using a function.