# `Backpex.Preferences.Adapters.Session`
[🔗](https://github.com/naymspace/backpex/blob/0.20.0/lib/backpex/preferences/adapters/session.ex#L1)

Session-backed `Backpex.Preferences` adapter.

Stores all preferences as a single nested map under one Phoenix session key
(`"backpex_preferences"`). Exact storage characteristics depend on the host
app's `Plug.Session` backend (cookie, ETS, Redis, ...). The default cookie
store has a ~4KB limit; prefer a database-backed adapter when you expect
bulky per-user data.

Reference implementation for the `Backpex.Preferences.Adapter` behavior — a
reasonable template when writing your own adapter.

## Size limit

With the default `:cookie` session store the browser caps the whole cookie —
Backpex's preferences *plus* everything the host app keeps in the session,
such as `phx.gen.auth`'s user token — at 4096 bytes. Past that,
`Plug.Session.COOKIE` raises `Plug.Conn.CookieOverflowError` and the request
500s. `put/4` therefore estimates the size of the resulting cookie and
refuses a write that would breach the budget with `{:error, :too_large}`,
leaving the stored value untouched;
`Backpex.PreferencesController` turns that into a `422` so the browser can
stop carrying the write. A warning is logged well before the ceiling.

### Options

  * `:max_bytes` — the wire budget for the encoded session, in bytes
    (default: `4096`, matching the cookie store). Use `:infinity` for a
    server-side session store (ETS, Redis, ...), which has no such cap:

        config :backpex, Backpex.Preferences,
          adapters: [
            {:default, Backpex.Preferences.Adapters.Session, max_bytes: :infinity}
          ]

The estimate covers the whole session, not just Backpex's subtree, and
accounts for the ~4/3 growth of Base64 plus the signature `Plug.Session`
adds. It is deliberately approximate: it is a budget check, not an exact
reproduction of the store's encoding. Prefer a database-backed adapter over
raising `:max_bytes` when per-user data genuinely does not fit.

## Write-path limitations

`put/4` returns `{:error, :requires_http}` for any source other than
`:controller`. `Plug.Session` cannot write to the Phoenix session outside
an HTTP request cycle. The dispatcher handles this by falling back to
`push_event/3`, which round-trips the write through the browser and the
preferences controller.

## `nil` values

`get/3` maps a stored `nil` to `{:ok, :not_found}`. Store a tagged value such
as `%{"value" => nil}` if application code must distinguish an explicit nil
from an absent preference.

# `session_key`

Returns the Phoenix session key used to store the preferences tree.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
