j-morgan6 avatar

elixir-phoenix-guide

Essential Elixir and Phoenix LiveView development guide with enforced skills, hooks, and patterns for idiomatic code

GitHub stars
175

Install

/plugin install elixir-phoenix-guide@elixir-phoenix-guide

Run it inside Claude Code after adding the marketplace with /plugin marketplace add j-morgan6/elixir-phoenix-guide.

Contents

Discovered from source

Skills 24

Code Quality

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Credo 1.7 — October 2026

On-demand checks for duplication and complexity. Nothing here runs automatically: the plugin's hooks check security and deprecated-API patterns on the lines Claude writes, not duplication, complexity or templates.

RULES — Follow these with no exceptions

  1. Run mix compile --warnings-as-errors first — the compiler reports unused private functions, variables, aliases and imports exactly; fix those before anything else
  2. Then run mix credo --strict when the project has Credo — its .credo.exs thresholds override the numbers in this skill
  3. Extract duplicated function bodies — when 2+ functions share a body that differs only in names or literals, keep one function and pass the differences as arguments
  4. Keep branch complexity low — split functions the analyzer flags (above 15) or Credo flags (CyclomaticComplexity, default max 9) into pattern-matched clauses or helpers
  5. Take a baseline before a large refactor — run the analyzer before and after, and compare
  6. Address duplication before complexity — extracting shared code often removes branches too
  7. Share code through plain modules — callers alias or import the shared module; don't build __using__ base modules just to share functions
  8. Repeated HEEx markup becomes a function component — a manual guideline; no tool checks templates

Order of tools

  1. mix compile --warnings-as-errors — unused code (the plugin no longer has its own unused-function check; the compiler is exact)
  2. mix credo --strict — the standard style and complexity checks. Refactor.CyclomaticComplexity is on by default (max 9); Design.DuplicatedCode and Refactor.ABCSize are opt-in in Credo's default config
  3. mix xref callers MyApp.Mod.fun/2 and mix xref graph — who uses a function or module across the project
  4. The plugin's analyzer (below) — duplication with renamed variables and changed literals across the whole tree, and a branch-complexity count for projects without Credo

Running the analyzer

The scripts ship with the plugin. They need only elixir (no deps, no compilation) and exit 1 when they find something. ${CLAUDE_SKILL_DIR} is this skill's own directory; Claude Code fills it in, and in other agents it means the folder containing this file.

# Whole project
elixir "${CLAUDE_SKILL_DIR}/../../scripts/code_quality.exs" scan lib/

# Umbrella: scan all apps in one pass so duplication across apps is found
elixir "${CLAUDE_SKILL_DIR}/../../scripts/code_quality.exs" scan apps/*/lib

# One file: complexity of that file, duplication against its whole lib/ tree
elixir "${CLAUDE_SKILL_DIR}/../../scripts/code_quality.exs" all lib/my_app_web/live/post_live/index.ex

# One check only
elixir "${CLAUDE_SKILL_DIR}/../../scripts/code_quality.exs" duplication lib/
elixir "${CLAUDE_SKILL_DIR}/../../scripts/code_quality.exs" complexity lib/my_app/reports.ex

# Wrapper: picks lib/ or apps/*/lib and reminds you of compile/credo first
bash "${CLAUDE_SKILL_DIR}/../../scripts/run_analysis.sh" .

Duplication

Two function bodies count as duplicates when their ASTs are identical after variable names are replaced and string/number literals are erased. Function names, arity, module and directory don't matter. Atoms, calls and structure must match. Bodies under 25 AST nodes are ignored.

Example output (from a fresh mix phx.gen.auth app):

Duplicated function bodies (identical after renaming variables and literals)

   deliver_update_email_instructions/2  lib/demo/accounts/user_notifier.ex:24
   deliver_magic_link_instructions/2  lib/demo/accounts/user_notifier.ex:51
   deliver_confirmation_instructions/2  lib/demo/accounts/user_notifier.ex:68

   Suggestion: extract one shared function (parameterize what differs).

Generated code like this is often fine to leave as it is. In your own code, extract the shared body:

defmodule MyApp.Reports.Summary do
  @moduledoc "Totals shared by the daily and weekly reports."

  def summarize(rows, label, precision) do
    {count, sum} = Enum.reduce(rows, {0, 0}, fn row, {c, s} -> {c + 1, s + row.amount} end)
    average = if count > 0, do: sum / count, else: 0
    %{total: sum, average: Float.round(average * 1.0, precision), label: label}
  end
end

# Callers:
#   MyApp.Reports.Summary.summarize(rows, "daily", 2)
#   MyApp.Reports.Summary.summarize(entries, "weekly", 3)

Limits: only exact matches after normalization are found, so a copy with one added line is missed (Credo's opt-in DuplicatedCode check with a mass_threshold catches near-copies). Each clause of a multi-clause function is compared on its own. Only .ex files are scanned.

Branch complexity

Branch complexity is 1, plus 1 for each if/unless, each -> clause (in case, cond, receive, fn and with ... else), each with, and each &&, ||, and, or. It approximates cyclomatic complexity. The threshold is 15. Credo's Refactor.CyclomaticComplexity is the standard check, and the project's .credo.exs limit takes precedence.

Example output:

High branch complexity (threshold 15)
   classify/3  lib/my_app/classifier.ex:2  branch complexity 16

   Suggestion: split into smaller functions or pattern-matched clauses.

How to fix: move each decision into a function head.

defmodule MyApp.Classifier do
  @moduledoc "Classifies pairs of numbers."

  def classify(a, b, _c) when a > 10 and b > 10, do: :both_big
  def classify(a, b, _c) when a > 10 or b > 10, do: :one_big
  def classify(a, a, :x), do: :same
  def classify(a, _b, c) when c == :y or a < 0, do: :odd
  def classify(a, b, _c), do: compare(a, b)

  defp compare(0, 0), do: :zero
  defp compare(0, _), do: :left_zero
  defp compare(_, 0), do: :right_zero
  defp compare(a, b) when a > b, do: :left
  defp compare(a, b) when a < b, do: :right
  defp compare(_, _), do: :tie
end

Repeated markup (manual)

No tool compares templates. When you notice the same block of markup in two or more templates, move it into a function component with declared attributes and slots:

defmodule MyAppWeb.MetricComponents do
  use Phoenix.Component

  attr :title, :string, required: true
  attr :range, :string, default: "7d"
  slot :inner_block, required: true

  def metric_panel(assigns) do
    ~H"""
    <section class="metric-panel">
      <h2>{@title} <span class="text-sm">({@range})</span></h2>
      {render_slot(@inner_block)}
    </section>
    """
  end
end

Use it in each template as <.metric_panel title="Cycle time" range={@range}>...</.metric_panel>.


Testing

For testing guidance, see the testing-essentials skill. When you extract shared code:

  • Keep the existing tests for every caller passing
  • Give the new shared module its own test file
  • Run mix test and mix compile --warnings-as-errors again afterwards: functions that are now unused show up as compiler warnings

Deployment Gotchas

Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14 — October 2026

Not a deployment guide. These are the things that break first Phoenix deploys, each tied to a real incident pattern.

RULES — Follow these with no exceptions

  1. Start from mix phx.gen.release --docker — it generates MyApp.Release, bin/migrate, bin/server and a Dockerfile in the right build order; don't hand-write them
  2. Environment values go in runtime.exs; compile-time settings stay in config/prod.exs — force_ssl and anything read with Application.compile_env can't be changed at boot
  3. Run migrations with bin/migrate before the new code takes traffic, and keep them backward-compatible — during a rolling deploy the old version runs against the new schema (expand, then contract in a later deploy)
  4. Start the server with bin/server (sets PHX_SERVER=true) and set PHX_HOST — runtime.exs enables the server only when PHX_SERVER is set; a wrong host breaks generated URLs and the websocket check_origin
  5. Build order is deps.compile → compile → assets.deploy → release — colocated hooks are extracted during mix compile, so assets built before compiling miss them
  6. Never hardcode secrets — read them in runtime.exs and fail at boot if missing
  7. Split health checks: liveness never touches the database, readiness does — and neither returns error details (inspect(reason) leaks hostnames)
  8. Behind a load balancer: keep force_ssl with rewrite_on: [:x_forwarded_proto], enable database SSL, keep check_origin
  9. Use config :logger, level: :info in production — :debug logs query parameters, which contain user data

1. Generate the Release Files

mix phx.gen.release --docker

It creates:

  • lib/my_app/release.ex — migrate/0 and rollback/2, runnable without Mix
  • rel/overlays/bin/migrate — runs ./my_app eval MyApp.Release.migrate
  • rel/overlays/bin/server — runs PHX_SERVER=true exec ./my_app start
  • Dockerfile and .dockerignore — a multi-stage build pinned to your Elixir/OTP versions

Hand-written release.ex files often use Application.load(@app). That returns {:error, {:already_loaded, _}} when the app is already loaded. The generator uses the idempotent Application.ensure_loaded/1:

# lib/my_app/release.ex (generated)
defp load_app do
  # Many platforms require SSL when connecting to the database
  Application.ensure_all_started(:ssl)
  Application.ensure_loaded(@app)
end

2. runtime.exs vs config.exs

The incident: DATABASE_URL is set correctly in production, but the release connects to the build machine's database, or to none.

Why: config.exs and prod.exs are evaluated when you build the release and baked into it. runtime.exs is evaluated at boot.

# config/prod.exs — runs on the build machine
config :my_app, MyApp.Repo, url: System.get_env("DATABASE_URL")
# config/runtime.exs
if config_env() == :prod do
  config :my_app, MyApp.Repo,
    url: System.fetch_env!("DATABASE_URL"),
    pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
end

The reverse mistake: some settings are read at compile time with Application.compile_env/3 and can't be changed at boot. Examples are the endpoint's force_ssl, code_reloader and debug_errors, and the generated :dev_routes. Set them in config.exs/prod.exs. If runtime.exs sets one to a different value, the release refuses to boot ("the application :my_app has a different value set for key ... during runtime compared to compile time").


3. Release Migrations and Rolling Deploys

The incident: a deploy renames users.name to users.full_name. For the two minutes when old and new instances both serve traffic, every request on the old instances 500s.

# In production — no Mix in a release
bin/migrate
# or: bin/my_app eval "MyApp.Release.migrate()"

Run it as a pre-deploy step (a release command, init container or job) before new instances start. Then the old version briefly runs against the new schema, so every migration must be safe for the code that's already deployed:

ChangeSafe sequence
Add a columnAdd it as nullable or with a default → deploy the code that writes it → backfill → add NOT NULL later
Rename a columnAdd the new column → write both → backfill → read the new one → drop the old one in a later deploy
Drop a columnStop reading it (remove it from the schema) → deploy → drop it in the next deploy
Add an index on a big tablecreate index(..., concurrently: true) with @disable_ddl_transaction true and @disable_migration_lock true

The exact migration code for each row (including NOT NULL without a full-table scan and lock_timeout) is in the ecto-migrations-safety skill.

Don't run migrations from Application.start/2. Every node would race to run them on boot.


4. PHX_SERVER, PHX_HOST and Networking

The incident: the release starts and the health check passes, but nothing listens on the port. Or emails link to https://example.com.

The generated runtime.exs already does the right thing:

# config/runtime.exs (generated)
if System.get_env("PHX_SERVER") do
  config :my_app, MyAppWeb.Endpoint, server: true
end

if config_env() == :prod do
  host = System.get_env("PHX_HOST") || "example.com"

  config :my_app, MyAppWeb.Endpoint,
    url: [host: host, port: 443, scheme: "https"],
    # IPv6 dual-stack: accepts IPv4 and IPv6 on all interfaces
    http: [ip: {0, 0, 0, 0, 0, 0, 0, 0}]
end
  • Start with bin/server, which sets PHX_SERVER=true. bin/my_app start alone boots the app without the HTTP listener. Keep the conditional rather than an unconditional server: true, so you can still boot a node without the listener (a worker-only node, or a bin/my_app start_iex maintenance console).
  • Set PHX_HOST. The fallback "example.com" produces wrong links and makes check_origin reject every websocket connection.
  • ECTO_IPV6=true makes the Repo connect over IPv6 (socket_options: [:inet6]). Fly.io's private network, for example, is IPv6-only.
  • DNS_CLUSTER_QUERY feeds the generated {DNSCluster, query: ...} child, which connects nodes for PubSub and Presence across instances. Without it each node is alone and broadcasts don't cross instances.

5. Docker Build Order

The incident: CSS and JS 404, or LiveView colocated hooks are missing from app.js.

The generated Dockerfile builds in this order. Keep it:

COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV
RUN mkdir config
COPY config/config.exs config/${MIX_ENV}.exs config/
RUN mix deps.compile
RUN mix assets.setup
COPY priv priv
COPY lib lib
# Compile first: colocated hooks/JS are extracted at compile time
RUN mix compile
COPY assets assets
RUN mix assets.deploy
# runtime.exs last: changing it doesn't invalidate the compile layers
COPY config/runtime.exs config/
COPY rel rel
RUN mix release

mix assets.deploy runs tailwind and esbuild with --minify, then phx.digest, which writes the priv/static/cache_manifest.json that prod.exs points the endpoint at. Compiling first matters for CSS too: app.css imports the phoenix-colocated CSS that mix compile writes (see the phoenix-tailwind-daisyui skill).


6. Never Hardcode Secrets

# config/prod.exs — in git history forever, baked into the release
config :my_app, MyAppWeb.Endpoint, secret_key_base: "actual_secret_key_here"
# config/runtime.exs
if config_env() == :prod do
  config :my_app, MyAppWeb.Endpoint, secret_key_base: System.fetch_env!("SECRET_KEY_BASE")
end

fetch_env! crashes at boot with a clear message. get_env returns nil and fails later in a confusing place. Generate a value with mix phx.gen.secret.


7. Behind a Load Balancer: TLS, Database SSL, Origins

  • HTTPS redirect and HSTS: the generated config/prod.exs has force_ssl: [rewrite_on: [:x_forwarded_proto], exclude: [hosts: ["localhost", "127.0.0.1"]]]. rewrite_on makes the app trust the proxy's x-forwarded-proto; without it every request looks like HTTP and you get a redirect loop. If the load balancer probes over plain HTTP, add the health paths: exclude: [paths: ["/health/live", "/health/ready"], hosts: [...]].
  • Database SSL: the generated runtime.exs leaves # ssl: true commented out. With Postgrex 0.21+, ssl: true verifies the server certificate against the OS CA store (:public_key.cacerts_get()). If you pass a keyword list instead (ssl: [...]), add cacerts: :public_key.cacerts_get() (or cacertfile: for a provider's private CA) yourself: the list form doesn't add CA certificates.
  • WebSocket origin: keep check_origin on; it compares the Origin header with url: [host: ...] (so PHX_HOST must be right), and several domains are listed explicitly. See the phoenix-channels-essentials skill.

8. Health Endpoints

The incident: a database blip makes every instance fail its health check. The orchestrator restarts the whole fleet, and the reconnect storm makes the outage longer.

Keep two checks with different jobs. Liveness ("is this BEAM alive?") must not touch the database. Failing it restarts the instance. Readiness ("can this instance serve?") queries the database. Failing it takes the instance out of rotation without restarting it.

# router.ex — outside :browser (no session/CSRF needed)
scope "/health", MyAppWeb do
  pipe_through :api

  get "/live", HealthController, :live
  get "/ready", HealthController, :ready
end
defmodule MyAppWeb.HealthController do
  use MyAppWeb, :controller

  alias Ecto.Adapters.SQL

  require Logger

  def live(conn, _params), do: send_resp(conn, 200, "ok")

  def ready(conn, _params) do
    case SQL.query(MyApp.Repo, "SELECT 1", [], timeout: 1_000) do
      {:ok, _} ->
        json(conn, %{status: "ok"})

      {:error, reason} ->
        # Details go to the log, never to the (often public) response
        Logger.error("Readiness check failed: #{inspect(reason)}")

        conn
        |> put_status(:service_unavailable)
        |> json(%{status: "unavailable"})
    end
  end
end

Point the liveness probe at /health/live and the readiness probe (or the load balancer's target health check) at /health/ready.


9. Production Log Level

The incident: log storage costs spike, and the logs contain full SQL parameters: emails and addresses.

The generated config/prod.exs sets config :logger, level: :info. Keep it. To allow a temporary override without a rebuild:

# config/runtime.exs
if config_env() == :prod do
  level =
    case System.get_env("LOG_LEVEL") do
      "debug" -> :debug
      "warning" -> :warning
      "error" -> :error
      _ -> :info
    end

  config :logger, level: level
end

At runtime on a live node you can also call Logger.configure(level: :debug) from bin/my_app remote, then set it back.


10. Oban in Releases

  • Oban's tables come from an ordinary Ecto migration that calls Oban.Migrations.up/1, so bin/migrate covers them. Oban upgrades that need a new migration version go through the same path.
  • To run jobs only on some nodes (for example worker nodes rather than web nodes), keep the queue list in config.exs and switch it off per node in runtime.exs with queues: false. The node starts no queues and can still insert jobs.
  • Don't use queues: [] for this: config files deep-merge keyword lists, and [] is an empty keyword list, so [default: 10] from config.exs survives the merge. For the same reason, a queues: [...] list in runtime.exs is merged into the config.exs list, not substituted for it.
# config/runtime.exs
if config_env() == :prod and System.get_env("OBAN_QUEUES") == "false" do
  config :my_app, Oban, queues: false
end

See the oban-essentials skill for Oban configuration.


Not Covered (Intentionally)

Platform specifics (Fly.io, Gigalixir, Render, Kubernetes manifests, CI pipelines) are covered in platform docs and the Phoenix deployment guides.


See the telemetry-essentials skill for production logging and observability. See the security-essentials skill for secrets, HTTPS and cookie settings.

Ecto Changeset Patterns

Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Create separate named changesets per operation — email_changeset, password_changeset, profile_changeset; never one changeset/2 that casts everything
  2. Never cast foreign keys or privileged fields (:user_id, :org_id, :role, :confirmed_at, :deleted_at) — set them with put_change/change from trusted code after a scope-checked lookup; for owned records use the Phoenix 1.8 changeset(struct, attrs, scope) shape
  3. Compose changesets with pipes — each validation step is a small private function reused across changesets
  4. Pair unsafe_validate_unique with unique_constraint — the first gives live form feedback, the second catches the race; both are case-sensitive unless the column is citext
  5. Use update_change/3 for normalisation (trim, downcase, slug) — in the changeset, never in the controller or LiveView; call it after validate_required
  6. Accept opts \\ [] to skip expensive steps during live validation — phx.gen.auth's validate_unique: false (no DB query per keystroke) and hash_password: false (no Bcrypt per keystroke)
  7. Passwords: min: 12, max: 72, plus max: 72, count: :bytes before hashing — Bcrypt only reads the first 72 bytes, and multibyte characters pass a character-count check
  8. Validate in the changeset, not in context functions — contexts stay thin wrappers around Repo calls

Separate Changesets Per Operation

The Phoenix 1.8 phx.gen.auth User schema already works this way. Here it is with a role added:

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :email, :string
    field :role, Ecto.Enum, values: [:member, :admin], default: :member
    field :password, :string, virtual: true, redact: true
    field :hashed_password, :string, redact: true
    field :confirmed_at, :utc_datetime
    field :authenticated_at, :utc_datetime, virtual: true

    timestamps(type: :utc_datetime)
  end

  # Generated. 1.8 registration is email-only (magic link) and register_user/1 uses
  # this changeset; to register extra fields, add a registration_changeset/3 that
  # pipes email_changeset/3 (see the phoenix-auth-customization skill).
  def email_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:email])
    |> validate_email(opts)
  end

  # Generated
  def password_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:password])
    |> validate_confirmation(:password, message: "does not match password")
    |> validate_password(opts)
  end

  # Privileged fields are never in a cast list. Trusted code sets them explicitly.
  # confirm_changeset/1 is generated; role_changeset/2 is yours.
  def confirm_changeset(user), do: change(user, confirmed_at: DateTime.utc_now(:second))

  def role_changeset(user, role) when role in [:member, :admin], do: change(user, role: role)
end

User-editable extras (username, profile fields) belong in their own changesets, registration_changeset/3 and profile_changeset/2 in the phoenix-auth-customization skill. If such a changeset cast :role or :confirmed_at, any user could promote or confirm themselves by adding a form field. Call role_changeset/2 only from an admin-only context function.

For records owned by a user, the 1.8 generators take the scope as the third argument and set the owner themselves:

def changeset(post, attrs, user_scope) do
  post
  |> cast(attrs, [:title, :body])
  |> validate_required([:title, :body])
  |> put_change(:user_id, user_scope.user.id)
end

Mass assignment: anything in a cast list can be set from a form or JSON body.

# A user can post user_id of another account, or folder_id of someone else's folder
|> cast(attrs, [:title, :folder_id, :user_id])

A foreign key the user chooses (folder_id) is set from a record loaded through the scope: folder = get_folder!(scope, folder_id), then put_change(:folder_id, folder.id) (see move_image/3 in the ecto-essentials skill).


Changeset Composition

The private validators phx.gen.auth generates for the changesets above:

defp validate_email(changeset, opts) do
  changeset =
    changeset
    |> validate_required([:email])
    |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
      message: "must have the @ sign and no spaces"
    )
    |> validate_length(:email, max: 160)

  if Keyword.get(opts, :validate_unique, true) do
    changeset
    |> unsafe_validate_unique(:email, MyApp.Repo)
    |> unique_constraint(:email)
    |> validate_email_changed()
  else
    changeset
  end
end

defp validate_email_changed(changeset) do
  if get_field(changeset, :email) && get_change(changeset, :email) == nil do
    add_error(changeset, :email, "did not change")
  else
    changeset
  end
end

defp validate_password(changeset, opts) do
  changeset
  |> validate_required([:password])
  |> validate_length(:password, min: 12, max: 72)
  |> maybe_hash_password(opts)
end

defp maybe_hash_password(changeset, opts) do
  hash_password? = Keyword.get(opts, :hash_password, true)
  password = get_change(changeset, :password)

  if hash_password? && password && changeset.valid? do
    changeset
    # Bcrypt truncates at 72 bytes; "é" is 2 bytes, so 72 characters can exceed it
    |> validate_length(:password, max: 72, count: :bytes)
    |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
    |> delete_change(:password)
  else
    changeset
  end
end

phx.gen.auth doesn't downcase emails: its migration makes email a citext column, so the unique index and unsafe_validate_unique already ignore case. Variant for a plain text/varchar email column (not the generator's code): normalise in the changeset and back it with a lower(email) unique index (see the ecto-essentials skill):

changeset
|> validate_required([:email])
|> update_change(:email, &String.downcase/1)
|> unique_constraint(:email, name: :users_lower_email_index)

update_change after validate_required is safe: validate_required drops a blank change, so the function never sees nil.


Conditional Validation with opts

opts exist so the same changeset can run cheaply on every phx-change and fully on submit:

# Context (generated) — passes opts through
def change_user_password(user, attrs \\ %{}, opts \\ []) do
  User.password_changeset(user, attrs, opts)
end

# Settings LiveView — runs on every keystroke: no Bcrypt
def handle_event("validate_password", %{"user" => user_params}, socket) do
  password_form =
    socket.assigns.current_scope.user
    |> Accounts.change_user_password(user_params, hash_password: false)
    |> to_form(action: :validate)

  {:noreply, assign(socket, password_form: password_form)}
end

On submit the context calls User.password_changeset(user, attrs) with the defaults, so the password is hashed. Registration works the same way: change_user_email(%User{}, params, validate_unique: false) on phx-change, the default (uniqueness checked) on insert.

  • hash_password: false keeps :password in the changes (so the form re-renders it) and skips the deliberately slow Bcrypt hash.
  • validate_unique: false skips unsafe_validate_unique's database query; unique_constraint still protects the insert.
  • Don't add options that skip validations to make tests faster — use the generated fixtures (see the testing-essentials skill).

Field Transformations with update_change

def changeset(post, attrs, scope) do
  post
  |> cast(attrs, [:title, :body])
  |> validate_required([:title, :body])
  |> update_change(:title, &String.trim/1)
  |> put_slug()
  |> put_change(:user_id, scope.user.id)
end

defp put_slug(changeset) do
  case get_change(changeset, :title) do
    nil ->
      changeset

    title ->
      slug = title |> String.downcase() |> String.replace(~r/[^a-z0-9]+/, "-") |> String.trim("-")
      put_change(changeset, :slug, slug)
  end
end

Nested Changesets

cast_assoc/cast_embed, child changesets that must not require the parent's foreign key, and editing child lists from <.inputs_for>: see the ecto-nested-associations skill.


Testing Changesets

describe "email_changeset/3" do
  test "requires email" do
    changeset = User.email_changeset(%User{}, %{})
    assert "can't be blank" in errors_on(changeset).email
  end

  test "rejects an email without @" do
    changeset = User.email_changeset(%User{}, %{email: "nope"}, validate_unique: false)
    assert "must have the @ sign and no spaces" in errors_on(changeset).email
  end
end

describe "password_changeset/3" do
  test "rejects 72 characters that exceed 72 bytes" do
    changeset = User.password_changeset(%User{}, %{password: String.duplicate("é", 72)})
    assert "should be at most 72 byte(s)" in errors_on(changeset).password
  end

  test "keeps the plain password when hash_password: false" do
    changeset = User.password_changeset(%User{}, %{password: "valid password"}, hash_password: false)
    assert get_change(changeset, :password) == "valid password"
    refute get_change(changeset, :hashed_password)
  end
end

See the ecto-essentials skill for schemas, scoped contexts and migrations. See the ecto-nested-associations skill for cast_assoc with nested data. See the testing-essentials skill for comprehensive testing patterns.

Ecto Essentials

Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Scope every context function — take %Scope{} first and filter by owner (Repo.get_by!(Post, id: id, user_id: scope.user.id)), as the Phoenix 1.8 generators do; never load, update or delete by a client-supplied id alone
  2. Never cast foreign keys or privileged fields (:user_id, :folder_id, :role, :org_id, :confirmed_at, :deleted_at) — set them with put_change/Ecto.build_assoc after a scope-checked lookup; use the 1.8 changeset(struct, attrs, scope) shape
  3. Always use changesets for inserts and updates — never pass raw maps to Repo
  4. Use Repo.transact/2 with with for multi-step writes; Repo.transaction/2 is soft-deprecated since Ecto 3.13. Reach for Ecto.Multi only when the steps are dynamic (see the ecto-nested-associations skill)
  5. Preload associations before accessing them — avoid N+1 queries
  6. Add database constraints AND changeset constraint functions — unique_index + unique_constraint, references + foreign_key_constraint
  7. Index every foreign key and every column you filter or sort on
  8. Use timestamps(type: :utc_datetime) in schemas and migrations — matches Phoenix 1.8's timestamp_type: :utc_datetime
  9. Escape %, _ and \ in user search terms before building a like/ilike pattern
  10. Keep change/0 migrations reversible — remove/3 with the type, modify with from:, execute/2 with an up and a down
  11. Database access goes through contexts — never call Repo from controllers or LiveViews

Schema and Changeset (1.8 scope pattern)

defmodule MyApp.Media.Image do
  use Ecto.Schema
  import Ecto.Changeset

  schema "images" do
    field :title, :string
    # Server-generated storage name (UUID + allowlisted extension)
    field :filename, :string
    # The client's file name, for display only
    field :original_name, :string
    # Detected from the file's bytes, not the client's claim
    field :content_type, :string
    field :byte_size, :integer

    belongs_to :folder, MyApp.Media.Folder
    belongs_to :user, MyApp.Accounts.User

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(image, attrs, scope) do
    image
    |> cast(attrs, [:title, :original_name])
    # filename/content_type/byte_size are set on the struct by the upload code
    # (see the phoenix-uploads skill); validate_required also checks struct data.
    |> validate_required([:title, :filename, :content_type, :byte_size])
    |> validate_length(:title, max: 255)
    |> put_change(:user_id, scope.user.id)
  end
end

This Image is the running example in the phoenix-uploads, phoenix-liveview-essentials (checklist) and testing-essentials (reference) skills too.

Mass assignment: anything in the cast list can be set from a form or JSON body (bad/good pair in the ecto-changeset-patterns skill). Set ownership from the scope and foreign keys from a record you loaded through the scope:

def move_image(%Scope{} = scope, %Image{} = image, folder_id) do
  true = image.user_id == scope.user.id
  folder = get_folder!(scope, folder_id)

  image
  |> Ecto.Changeset.change(folder_id: folder.id)
  |> Ecto.Changeset.foreign_key_constraint(:folder_id)
  |> Repo.update()
end

Context Pattern (scoped)

To generate this shape, or an org-scoped variant with --scope org, see the phoenix-scopes-and-generators skill.

Mirror mix phx.gen.context in 1.8: scope first, owner filter on every read, ownership assert on every write. (The generator also broadcasts {:created | :updated | :deleted, image} after each write; see the phoenix-pubsub-patterns skill.)

defmodule MyApp.Media do
  import Ecto.Query, warn: false

  alias MyApp.Accounts.Scope
  alias MyApp.Media.{Folder, Image}
  alias MyApp.Repo

  # filters: [folder_id: id, search: term, min_size: bytes] (see Query Composition)
  def list_images(%Scope{} = scope, filters \\ []) do
    Image
    |> where(user_id: ^scope.user.id)
    |> filter_images(filters)
    |> order_by(desc: :inserted_at, desc: :id)
    |> Repo.all()
  end

  def get_image!(%Scope{} = scope, id) do
    Repo.get_by!(Image, id: id, user_id: scope.user.id)
  end

  def get_folder!(%Scope{} = scope, id) do
    Repo.get_by!(Folder, id: id, user_id: scope.user.id)
  end

  # tmp_path is the upload's temp file; store_file/1 checks its magic bytes,
  # names it on the server and copies it. Storage fields never go through cast.
  def create_image(%Scope{} = scope, tmp_path, attrs) do
    with {:ok, stored} <- store_file(tmp_path) do
      Image
      |> struct!(stored)
      |> Image.changeset(attrs, scope)
      |> Repo.insert()
    end
  end

  def update_image(%Scope{} = scope, %Image{} = image, attrs) do
    true = image.user_id == scope.user.id

    image
    |> Image.changeset(attrs, scope)
    |> Repo.update()
  end

  # For uploaded files, the phoenix-uploads version also removes the stored file.
  def delete_image(%Scope{} = scope, %Image{} = image) do
    true = image.user_id == scope.user.id
    Repo.delete(image)
  end

  # Private helpers not shown: filter_images/2 (Query Composition below) and
  # store_file/1 (the phoenix-uploads skill).
end
# IDOR: any logged-in user can read or delete any image by guessing ids
def get_image!(id), do: Repo.get!(Image, id)

LiveViews and controllers pass socket.assigns.current_scope / conn.assigns.current_scope.

Query Composition

def search_images(%Scope{} = scope, term) do
  pattern = "%" <> escape_like(term) <> "%"

  Image
  |> where(user_id: ^scope.user.id)
  |> where([i], ilike(i.title, ^pattern) or ilike(i.original_name, ^pattern))
  |> order_by(desc: :inserted_at, desc: :id)
  |> Repo.all()
end

# `%` and `_` are LIKE wildcards; `\` is Postgres's default LIKE escape character.
# Unescaped, a search for "_" matches every row.
defp escape_like(term), do: String.replace(term, ["\\", "%", "_"], &("\\" <> &1))

Dynamic filters for list_images(scope, filters) above — reduce over an allowlist of keys; unknown keys fall through:

defp filter_images(query, filters) do
  Enum.reduce(filters, query, fn
    {:folder_id, folder_id}, query -> where(query, [i], i.folder_id == ^folder_id)
    {:search, term}, query -> where(query, [i], ilike(i.title, ^"%#{escape_like(term)}%"))
    {:min_size, size}, query -> where(query, [i], i.byte_size >= ^size)
    _, query -> query
  end)
end

To get one row from a query that may match several, use query |> first() |> Repo.one() (or limit(1)); Repo.one/1 raises Ecto.MultipleResultsError on more than one row.

Preloading Associations

images = Repo.all(Image)
# image.folder is %Ecto.Association.NotLoaded{} — and loading it per row is N+1
Enum.map(images, fn image -> image.folder.name end)
images =
  Image
  |> where(user_id: ^scope.user.id)
  |> preload(:folder)
  |> Repo.all()

When you also filter on the association, join and preload from the join in one query: join(query, :inner, [i], f in assoc(i, :folder)) |> preload([_i, f], folder: f).

Join-preload vs separate-query trade-offs, per-parent limits and N+1 detection: see the ecto-queries-performance skill.

Transactions — Repo.transact/2

The function must return {:ok, value} (commit) or {:error, reason} (rollback); transact returns that value unchanged, so a plain with is the whole pattern.

def create_folder_with_images(%Scope{} = scope, attrs, image_ids) do
  Repo.transact(fn ->
    with {:ok, folder} <- create_folder(scope, attrs) do
      {count, _} =
        Image
        |> where([i], i.id in ^image_ids and i.user_id == ^scope.user.id)
        |> Repo.update_all(set: [folder_id: folder.id, updated_at: DateTime.utc_now(:second)])

      {:ok, %{folder: folder, moved: count}}
    end
  end)
end
  • {:error, changeset} from create_folder/2 falls out of with and rolls back — no Repo.rollback/1 or catch-all else needed.
  • update_all skips changesets and autogenerated timestamps: set updated_at yourself, and keep the scope filter in the query.
  • Use Ecto.Multi when the number of steps depends on input (one step per cart item, etc.) — see the ecto-nested-associations skill.

Upserts

# Migration: create unique_index(:tags, [:user_id, :name])
def upsert_tag(%Scope{} = scope, attrs) do
  %Tag{}
  |> Tag.changeset(attrs, scope)
  |> Repo.insert(
    on_conflict: {:replace_all_except, [:id, :inserted_at]},
    conflict_target: [:user_id, :name],
    returning: true
  )
end
  • conflict_target must match a unique index exactly; its columns are never rewritten (replace_changed: true is the default).
  • {:replace_all_except, ...} overwrites every other column with the changeset's values, including fields the caller left unset. To touch only some columns use {:replace, [:color, :updated_at]} — never list the conflict-target columns there.
  • Without returning: true the returned struct holds the values you tried to insert (e.g. a fresh inserted_at), not the row in the database.

Unique Constraints

# Migration
create unique_index(:folders, [:user_id, :name])

# Changeset — both: unsafe_validate_unique for live feedback, unique_constraint for the race
|> unsafe_validate_unique([:name, :user_id], MyApp.Repo)
|> unique_constraint(:name, name: :folders_user_id_name_index)

Case-insensitive uniqueness (emails, usernames): a plain unique_index and unsafe_validate_unique are case-sensitive, so Bob@x.com and bob@x.com both get in. Either use a citext column (what phx.gen.auth does), or a functional index plus downcasing in the changeset:

# Option 1 — citext (comparisons, the unique index and unsafe_validate_unique all ignore case)
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
alter table(:accounts) do
  add :email, :citext, null: false
end
create unique_index(:accounts, [:email])

# Option 2 — expression index; downcase in the changeset so unsafe_validate_unique agrees
create unique_index(:accounts, ["(lower(email))"], name: :accounts_lower_email_index)
# |> update_change(:email, &String.downcase/1)
# |> unique_constraint(:email, name: :accounts_lower_email_index)

Migrations

defmodule MyApp.Repo.Migrations.CreateImages do
  use Ecto.Migration

  def change do
    create table(:images) do
      add :title, :string, null: false
      add :filename, :string, null: false
      add :original_name, :string
      add :content_type, :string, null: false
      add :byte_size, :integer, null: false
      add :user_id, references(:users, on_delete: :delete_all), null: false
      add :folder_id, references(:folders, on_delete: :nilify_all)

      timestamps(type: :utc_datetime)
    end

    create index(:images, [:user_id])
    create index(:images, [:folder_id])
    create unique_index(:images, [:filename])
    create constraint(:images, :byte_size_must_be_positive, check: "byte_size > 0")
  end
end

Irreversible commands in change/0 — they migrate fine and raise Ecto.MigrationError on rollback:

def change do
  alter table(:images) do
    remove :legacy_path
    modify :title, :text
  end

  execute "CREATE EXTENSION IF NOT EXISTS pg_trgm"
end
def change do
  alter table(:images) do
    remove :legacy_path, :string
    modify :title, :text, from: :string
  end

  execute "CREATE EXTENSION IF NOT EXISTS pg_trgm", "DROP EXTENSION IF EXISTS pg_trgm"
end

For data backfills or anything without a natural inverse, write up/0 and down/0.

For tables with live traffic (concurrent indexes, lock_timeout, NOT NULL and foreign keys without long locks, backfills), see the ecto-migrations-safety skill.

Reference

Field types (:decimal, Ecto.Enum, {:array, t}…), validator and constraint cheat sheets, query syntax (joins, aggregates, null ordering), migration operations and soft delete: see the Ecto reference.

cast_assoc, nested forms, Ecto.Multi and on_delete design: see the ecto-nested-associations skill. Multiple changesets per schema and conditional validation: see the ecto-changeset-patterns skill.

Testing

When writing tests for Ecto schemas, changesets, or contexts, invoke elixir-phoenix-guide:testing-essentials before writing any _test.exs file.

Ecto Migrations Safety

Verified against Elixir 1.20, Ecto 3.14 (ecto_sql 3.14), PostgreSQL 16 — October 2026

RULES — Follow these with no exceptions

  1. Index existing tables with concurrently: true plus both @disable_ddl_transaction true and @disable_migration_lock true, one index per migration. With only the first, the migration hangs forever under the default migration lock.
  2. Set lock_timeout in every transactional migration that alters a busy table: after_begin/0 calling repo().query!("SET LOCAL lock_timeout TO '5s'"). Never execute/1 there, because it breaks rollback of change/0.
  3. Add columns as nullable or with a constant default. A volatile default (gen_random_uuid(), clock_timestamp(), random()) rewrites the whole table under an exclusive lock.
  4. NOT NULL takes three migrations: CHECK (col IS NOT NULL) with validate: false, then VALIDATE CONSTRAINT, then SET NOT NULL through execute/2. Don't use modify ... null: false for this step: it also emits ALTER COLUMN TYPE, which rescans the table.
  5. Add foreign keys and check constraints to populated tables with validate: false, then validate them in a later migration.
  6. Never rename or drop anything the running code reads. Expand and contract across deploys. To rename only in Elixir, use field :new_name, :string, source: :old_column.
  7. Change a type in place only when PostgreSQL can skip the rewrite (varchar → text). Any other change (integer → bigint) gets a new column, a backfill and a switch.
  8. Backfill in a separate data migration: schemaless (from p in "posts"), batched, outside a DDL transaction. Never call app schemas or contexts from a migration.
  9. Make every migration reversible (execute/2, modify ... from:, remove/3 with a type) or write up/0/down/0. Keep migrations without a transaction to a single idempotent step, because they can fail half-applied.
  10. Run migrations before the new code takes traffic (see the deployment-gotchas skill), and read the generated SQL with mix ecto.migrate --log-migrations-sql before you ship.

Why "it worked locally" isn't enough: the lock queue

Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock. On a busy table, the danger isn't how long the DDL takes. It's the time spent waiting for the lock: while an ALTER waits behind one long-running query or idle transaction, every later SELECT on that table queues behind the ALTER. A 2 ms change becomes a full outage. Two fixes cover most cases:

  • don't hold the lock for long: no table rewrites, no full scans under ACCESS EXCLUSIVE
  • don't wait for it for long: set lock_timeout, let the migration fail, and retry later
Operation (PostgreSQL 12+)Rewrite or scan?Blocks reads and writes?
add :col, :type (nullable, no default)nobriefly
add :col, :type, default: "constant" (constant default, even with null: false)nobriefly
add :col, :uuid, default: fragment("gen_random_uuid()")rewritefor the whole rewrite
modify :title, :text, from: :string (varchar → text)nobriefly
integer → bigint, or any other non-binary-compatible typerewritefor the whole rewrite
SET NOT NULLfull scan, unless a validated CHECK (col IS NOT NULL) existsfor the scan
create constraint(..., validate: false) / references(..., validate: false)nobriefly
VALIDATE CONSTRAINTscanno (SHARE UPDATE EXCLUSIVE)
create indexscanblocks writes for the build
create index(..., concurrently: true)scanno
rename, removenobriefly, but breaks old code

The rewrite and scan rows were measured on a 2M-row table (relfilenode changes, DEBUG output). Lock levels come from the PostgreSQL ALTER TABLE docs.

Concurrent indexes

defmodule MyApp.Repo.Migrations.AddPostsSlugIndex do
  use Ecto.Migration
  @disable_ddl_transaction true
  @disable_migration_lock true

  def change do
    create index(:posts, [:slug], concurrently: true)
  end
end

Rolling it back emits DROP INDEX CONCURRENTLY. Here is why both attributes are needed (each case tested):

AttributesResult
neitherERROR 25001 CREATE INDEX CONCURRENTLY cannot run inside a transaction block
only @disable_ddl_transactionhangs forever. The default migration_lock: :table_lock keeps a transaction open on schema_migrations for the whole run, while the migration runs in a separate process. CREATE INDEX CONCURRENTLY waits for every older transaction to finish, including that one (wait_event = virtualxid). Ecto only prints an IO.warn
bothworks
only @disable_ddl_transaction, plus repo migration_lock: :pg_advisory_lockworks, no warning
  • @disable_migration_lock true lets two nodes run the same migration at the same time. That's fine when one pre-deploy job runs migrations. If every node migrates on boot, set config :my_app, MyApp.Repo, migration_lock: :pg_advisory_lock instead. It's session-level, so it doesn't work behind PgBouncer in transaction pooling mode.
  • concurrently is only for tables that already hold data. An index in the same migration as create table needs neither attribute.
  • A failed concurrent build leaves an INVALID index behind. For example, create unique_index(..., concurrently: true) fails on duplicate rows. Re-running the migration then fails with 42P07 relation "..." already exists. Find it with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid, run DROP INDEX CONCURRENTLY name, fix the data and migrate again.
  • The build waits for long-running and idle-in-transaction sessions to finish. It doesn't block traffic while it waits, but the deploy stalls.

lock_timeout

defmodule MyApp.Repo.Migrations.AddPostsStatus do
  use Ecto.Migration

  def after_begin do
    repo().query!("SET LOCAL lock_timeout TO '5s'")
  end

  def change do
    alter table(:posts) do
      add :status, :string, default: "draft", null: false
    end
  end
end

If another session holds a conflicting lock for more than 5 s, the migration fails with 55P03 lock_not_available and rolls back. The table is untouched; retry the deploy.

  • after_begin/0 runs right after the migration transaction opens, on up and on down. SET LOCAL limits the setting to that transaction. A plain SET would stay on the pooled connection.
  • Use repo().query! and not execute "SET ...". after_begin/0 runs in the same direction as change/0, so on rollback Ecto tries to reverse the execute/1 and raises cannot reverse migration command.
  • after_begin/0 doesn't run in @disable_ddl_transaction migrations, and a plain repo().query!("SET lock_timeout ...") there doesn't stick either: every command may check out a different pooled connection (tested: the setting alternated between two backends). Pin one connection with repo().checkout/1. See the migrations safety reference.
  • To apply it to every migration, use the pattern from the Ecto.Migration docs: a MyApp.Migration module whose __using__/1 does use Ecto.Migration and defines after_begin/0. Then use MyApp.Migration in each migration.
  • Ecto runs migration DDL with no client timeout (timeout: :infinity), but a statement_timeout set on the database role still applies. If your role has one, scans like VALIDATE and index builds can be cancelled. Override it in that migration with SET LOCAL statement_timeout TO 0.

NOT NULL on an existing column

# 1. Enforced for new writes from now on; existing rows aren't checked
def change do
  create constraint(:posts, :posts_title_not_null, check: "title IS NOT NULL", validate: false)
end
# 2. A separate migration, so the scan runs without the ACCESS EXCLUSIVE lock from step 1
def change do
  execute "ALTER TABLE posts VALIDATE CONSTRAINT posts_title_not_null", ""
end
# 3. PostgreSQL 12+ sees the validated CHECK and skips the scan
def change do
  execute "ALTER TABLE posts ALTER COLUMN title SET NOT NULL",
          "ALTER TABLE posts ALTER COLUMN title DROP NOT NULL"

  execute "ALTER TABLE posts DROP CONSTRAINT posts_title_not_null",
          "ALTER TABLE posts ADD CONSTRAINT posts_title_not_null CHECK (title IS NOT NULL) NOT VALID"
end
  • Backfill any NULLs before step 2, or VALIDATE fails.
  • Steps 1 and 2 must be separate migrations. In one transaction, the ACCESS EXCLUSIVE lock from ADD CONSTRAINT is held for the whole validating scan.
  • Step 3 measured: about 0.3 ms with execute against about 55 ms for modify :title, :string, null: false, from: {:string, null: true} on 2M rows. The modify form generates ALTER COLUMN "title" TYPE varchar(255), ALTER COLUMN "title" SET NOT NULL, and the TYPE clause makes PostgreSQL verify the table again.
  • drop constraint/2 can't be reversed in change/0, so step 3 uses execute/2 for both statements.

Foreign keys and check constraints

# Migration 1: new column with a foreign key that skips the existing-rows check
alter table(:posts) do
  add :editor_id, references(:users, on_delete: :nilify_all, validate: false)
end
# Migration 2
def change do
  execute "ALTER TABLE posts VALIDATE CONSTRAINT posts_editor_id_fkey", ""
end
  • references(..., validate: false) generates ... REFERENCES "users"("id") ON DELETE SET NULL NOT VALID (PostgreSQL only). Adding a validated foreign key locks out writes on both tables while it scans.
  • For an existing column, modify :reviewer_id, references(:users, validate: false), from: :bigint works. It emits a no-op ALTER COLUMN TYPE bigint along with ADD CONSTRAINT ... NOT VALID.
  • The constraint name is <table>_<column>_fkey unless you pass name:. create constraint(..., check: ..., validate: false) works the same way for check constraints.
  • Indexing the new foreign key column is a separate concurrent-index migration.

Renames, type changes, drops: expand and contract

During a rolling deploy, old instances run against the new schema. Ecto names every schema field in its SQL (SELECT p0."id", p0."title" ...), so a renamed or dropped column fails every query from old instances with undefined_column.

ChangeSteps (each one is its own deploy)
Rename a columnadd the new column → write both → backfill → read the new one → stop writing the old one → drop it
Rename only in codefield :headline, :string, source: :title, no migration
Change a type (integer → bigint)same as a rename: new column, dual-write, backfill, switch reads, drop
Drop a columnremove the field from the schema and deploy → drop the column in the next deploy
Rename a tablecreate the new table, dual-write and backfill, or keep the old name and set schema "old_name"
Add a NOT NULL columnadd it nullable or with a constant default, so old code's inserts still work

Dual writes go in the changeset or context function (put_change/3 on both fields), not in a database trigger you'll forget to remove.

Backfills

# Breaks on a fresh database once Post gains a field this migration predates,
# and holds one transaction (and its row locks) for the whole update
def change do
  alter table(:posts), do: add(:slug, :text)
  flush()
  MyApp.Repo.update_all(MyApp.Blog.Post, set: [slug: "x"])
end
defmodule MyApp.Repo.Migrations.BackfillPostSlugs do
  use Ecto.Migration
  import Ecto.Query

  @disable_ddl_transaction true
  @disable_migration_lock true
  @batch_size 10_000

  def up, do: backfill(0)

  def down, do: :ok

  defp backfill(last_id) do
    ids =
      repo().all(
        from(p in "posts",
          where: p.id > ^last_id and is_nil(p.slug),
          order_by: p.id,
          limit: @batch_size,
          select: p.id
        ),
        log: false
      )

    case ids do
      [] ->
        :ok

      ids ->
        repo().update_all(
          from(p in "posts", where: p.id in ^ids, update: [set: [slug: fragment("lower(?)", p.title)]]),
          [],
          log: false
        )

        backfill(List.last(ids))
    end
  end
end
  • Each batch commits on its own, so row locks are short and a failure keeps the progress made so far. The is_nil filter makes a re-run continue where it stopped. Tested: 2M rows in about 11 s.
  • Use the table name ("posts"), never MyApp.Blog.Post. Migrations run against the schema as it was at that version, and app modules change after the migration is written.
  • Optional: keep data migrations in priv/repo/data_migrations and run them with mix ecto.migrate --migrations-path priv/repo/data_migrations, or Ecto.Migrator.run(repo, Ecto.Migrator.migrations_path(repo, "data_migrations"), :up, all: true) from your Release module. They share schema_migrations, so mix ecto.migrations lists their versions as ** FILE NOT FOUND ** unless you pass the path.
  • For very large tables, or work that needs app logic (slugs that must be unique, external calls), enqueue an Oban job that processes batches and re-enqueues itself. See the oban-essentials skill.

Reversibility and partial failure

The basics (remove/3 with a type, modify ... from:, execute/2) are in the ecto-essentials skill. Specific to safe migrations:

  • drop constraint, remove_if_exists, execute/1 and flush() can't run backward inside change/0. flush() raises calling flush() inside change when doing rollback is not supported, so write up/0 and down/0.
  • @disable_ddl_transaction means no rollback on error. Ecto records the version only after the whole migration succeeds, so with two statements where the second fails, the first stays applied and the next run repeats it. Keep these migrations to one statement, or make every step idempotent (create_if_not_exists, IF NOT EXISTS).
  • mix ecto.migrate --step 1 applies one migration and mix ecto.rollback reverts one by default (--step n, --to version, --all). In production, roll back with the Release module's rollback/2.

Tooling

  • mix ecto.migrate --log-migrations-sql prints the SQL each migration command generates. --log-migrator-sql also prints the migrator's own begin/LOCK TABLE/advisory-lock statements. Run them against a dev copy before shipping.
  • mix ecto.migrations shows which migrations are up and which are down.
  • Hex linters such as excellent_migrations and strong_migrations flag many of these patterns in CI.
  • ecto_sql 3.14's docs include a "Safe Ecto Migrations" guide with more recipes.

More recipes (lock_timeout for concurrent indexes, lock-level details, a pre-merge checklist) are in the migrations safety reference.

Ecto Nested Associations

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Use cast_assoc/3 / cast_embed/3 for children edited with their parent — never insert children in a separate step; Ecto sets the foreign key
  2. Child changesets never cast or require the parent's foreign key — cast_assoc sets it after the parent is inserted; requiring it gives "can't be blank"
  3. on_replace is an option on the association, not on cast_assoc — has_many :items, Item, on_replace: :delete. The default is :raise: omitting an existing child from the params raises
  4. Load the parent through the scope and preload before casting — cast_assoc/3 raises on %Ecto.Association.NotLoaded{}
  5. Edit child lists from <.inputs_for> with :sort_param / :drop_param — plus on_replace: :delete, and a with: function of arity 3 when order must persist
  6. Repo.transact/2 + with for a fixed set of steps; Ecto.Multi when the steps depend on input (one step per cart item)
  7. Never read-check-write a counter — decrement with update_all guarded by where: p.stock >= ^qty and check the affected count is 1
  8. Choose on_delete deliberately — :delete_all for owned children, :nilify_all (nullable column) to keep them, :restrict + no_assoc_constraint/3 to block; the default :nothing also blocks the delete
  9. Index every foreign key column — deleting a parent otherwise scans the child table

Schemas for a Nested Form

defmodule MyApp.Recipes.Recipe do
  use Ecto.Schema
  import Ecto.Changeset

  alias MyApp.Recipes.Ingredient

  schema "recipes" do
    field :name, :string
    field :user_id, :id

    has_many :ingredients, Ingredient,
      on_replace: :delete,
      preload_order: [asc: :position]

    timestamps(type: :utc_datetime)
  end

  def changeset(recipe, attrs, scope) do
    recipe
    |> cast(attrs, [:name])
    |> validate_required([:name])
    |> cast_assoc(:ingredients,
      with: &Ingredient.changeset/3,
      sort_param: :ingredients_sort,
      drop_param: :ingredients_drop
    )
    |> put_change(:user_id, scope.user.id)
  end
end

defmodule MyApp.Recipes.Ingredient do
  use Ecto.Schema
  import Ecto.Changeset

  schema "ingredients" do
    field :name, :string
    field :quantity, :string
    field :position, :integer
    belongs_to :recipe, MyApp.Recipes.Recipe

    timestamps(type: :utc_datetime)
  end

  # Arity 3: cast_assoc passes the item's final position (nil when it is being replaced).
  # This third argument is the position, not the 1.8 scope; children get ownership via the parent.
  def changeset(ingredient, attrs, position) do
    ingredient
    |> cast(attrs, [:name, :quantity])
    |> validate_required([:name])
    |> change(position: position)
  end
end
# Child changeset that casts and requires the parent FK: "recipe_id can't be blank" on create,
# and a client could re-parent an ingredient onto someone else's recipe
def changeset(ingredient, attrs) do
  ingredient
  |> cast(attrs, [:name, :quantity, :recipe_id])
  |> validate_required([:name, :recipe_id])
end
# on_replace is not a cast_assoc option — the association keeps its :raise default
|> cast_assoc(:ingredients, on_replace: :delete)

Context: Create and Update

def get_recipe!(%Scope{} = scope, id) do
  Recipe
  |> Repo.get_by!(id: id, user_id: scope.user.id)
  |> Repo.preload(:ingredients)
end

# A new %Recipe{} needs no preload — built structs cast children against []
def create_recipe(%Scope{} = scope, attrs) do
  %Recipe{}
  |> Recipe.changeset(attrs, scope)
  |> Repo.insert()
end

def update_recipe(%Scope{} = scope, %Recipe{} = recipe, attrs) do
  true = recipe.user_id == scope.user.id

  recipe
  |> Repo.preload(:ingredients)
  |> Recipe.changeset(attrs, scope)
  |> Repo.update()
end

With on_replace: :delete, children are matched by id: given ingredients A, B, C and params %{"ingredients" => [%{"id" => a.id, "name" => "A2"}, %{"name" => "D"}]}, A is updated, B and C are deleted, D is inserted.

recipe = Repo.get_by!(Recipe, id: id, user_id: scope.user.id)
# ingredients is %Ecto.Association.NotLoaded{} — cast_assoc inside Recipe.changeset/3 raises
# "attempting to cast or change association `ingredients` ... that was not loaded",
# before Repo.update/1 is ever called
recipe |> Recipe.changeset(attrs, scope) |> Repo.update()

Editing Child Lists with <.inputs_for>

The supported way to add, remove and reorder children from a LiveView form. Ecto reads ingredients_sort / ingredients_drop from the params (names must match the cast_assoc options):

<.form for={@form} id="recipe-form" phx-change="validate" phx-submit="save">
  <.input field={@form[:name]} type="text" label="Name" />

  <.inputs_for :let={f_ing} field={@form[:ingredients]}>
    <input type="hidden" name="recipe[ingredients_sort][]" value={f_ing.index} />
    <.input field={f_ing[:name]} type="text" placeholder="Ingredient" />
    <.input field={f_ing[:quantity]} type="text" placeholder="Quantity" />
    <button
      type="button"
      name="recipe[ingredients_drop][]"
      value={f_ing.index}
      phx-click={JS.dispatch("change")}
    >
      Remove
    </button>
  </.inputs_for>

  <input type="hidden" name="recipe[ingredients_drop][]" />

  <button
    type="button"
    name="recipe[ingredients_sort][]"
    value="new"
    phx-click={JS.dispatch("change")}
  >
    Add ingredient
  </button>

  <.button phx-disable-with="Saving...">Save</.button>
</.form>
  • value="new" in the sort param appends an empty child; a dropped index removes that child. JS.dispatch("change") routes the click through phx-change, so the validate handler re-renders the list — no add/remove events needed.
  • The empty hidden ..._drop[] input outside inputs_for is required: without it, removing the last child sends no ingredients key and nothing is deleted.
  • Both buttons need type="button", or they submit the form.
  • :drop_param requires on_replace: :delete on the association. For has_many, persisted order needs the position field set by the arity-3 with: (embeds keep list order on their own).

cast_embed for Embedded Schemas

Same API, stored as JSON in one column (no table, no foreign key):

defmodule MyApp.Profiles.Profile do
  use Ecto.Schema
  import Ecto.Changeset

  alias MyApp.Profiles.SocialLink

  schema "profiles" do
    field :name, :string
    embeds_many :social_links, SocialLink, on_replace: :delete

    timestamps(type: :utc_datetime)
  end

  def changeset(profile, attrs) do
    profile
    |> cast(attrs, [:name])
    |> cast_embed(:social_links,
      with: &SocialLink.changeset/2,
      sort_param: :social_links_sort,
      drop_param: :social_links_drop
    )
  end
end

defmodule MyApp.Profiles.SocialLink do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key false
  embedded_schema do
    field :platform, :string
    field :url, :string
  end

  def changeset(link, attrs) do
    link
    |> cast(attrs, [:platform, :url])
    |> validate_required([:platform, :url])
    |> validate_format(:url, ~r/^https?:\/\//)
  end
end

Multi-Table Writes: Repo.transact or Ecto.Multi

For a fixed sequence of steps, a with inside Repo.transact/2 is simpler (see the ecto-essentials skill). Ecto.Multi earns its place when the number of steps depends on the input — here, one stock reservation per cart line:

defmodule MyApp.Orders do
  import Ecto.Query, warn: false

  alias Ecto.Multi
  alias MyApp.Accounts.Scope
  alias MyApp.Catalog.Product
  alias MyApp.Orders.{LineItem, Order}
  alias MyApp.Repo

  # cart_items: [%{product_id: id, quantity: qty}] — prices are read from the database
  def place_order(%Scope{} = scope, cart_items) do
    Multi.new()
    |> Multi.insert(:order, Order.changeset(%Order{}, %{}, scope))
    |> reserve_stock(cart_items)
    |> Multi.insert_all(:line_items, LineItem, &line_item_rows/1)
    |> Repo.transact()
  end

  defp reserve_stock(multi, cart_items) do
    cart_items
    |> Enum.with_index()
    |> Enum.reduce(multi, fn {%{product_id: product_id, quantity: qty}, i}, multi ->
      Multi.run(multi, {:reserve, i}, fn repo, _changes -> reserve(repo, product_id, qty) end)
    end)
  end

  defp reserve(_repo, _product_id, qty) when not is_integer(qty) or qty <= 0,
    do: {:error, :invalid_quantity}

  defp reserve(repo, product_id, qty) do
    query =
      from p in Product,
        where: p.id == ^product_id and p.stock >= ^qty,
        select: p.price

    # Check and decrement in one statement: no row matches when stock is short,
    # so two concurrent orders can't both take the last item
    case repo.update_all(query, inc: [stock: -qty]) do
      {1, [price]} -> {:ok, %{product_id: product_id, quantity: qty, price: price}}
      {0, _} -> {:error, :insufficient_stock}
    end
  end

  defp line_item_rows(%{order: order} = changes) do
    now = DateTime.utc_now(:second)

    for {{:reserve, _}, item} <- changes do
      Map.merge(item, %{order_id: order.id, inserted_at: now, updated_at: now})
    end
  end
end

Handling the result — a failed Multi returns {:error, step_name, value, changes_so_far} and nothing is committed:

case Orders.place_order(scope, cart_items) do
  {:ok, %{order: order}} -> {:ok, order}
  {:error, :order, %Ecto.Changeset{} = changeset, _changes} -> {:error, changeset}
  {:error, {:reserve, _index}, reason, _changes} -> {:error, reason}
end
# Race: two requests both read stock = 1, both pass, both decrement → stock = -1
|> Multi.run(:check, fn _repo, _ -> if sufficient_stock?(items), do: {:ok, :ok}, else: {:error, :out} end)
|> Multi.update(:decrement_stock, fn _ -> decrement_stock_changeset(items) end)
  • insert_all/update_all skip changesets and autogenerated timestamps — set inserted_at/updated_at yourself (DateTime for :utc_datetime schemas).
  • They also don't turn constraint violations into errors: a bad foreign key in insert_all raises Postgrex.Error out of Repo.transact/2 rather than returning {:error, ...}. Make failures you expect go through a step that returns {:error, reason}, as reserve/3 does.
  • Duplicate step names raise, which is why the steps are keyed {:reserve, index}.

Foreign Keys and on_delete

defmodule MyApp.Repo.Migrations.CreateComments do
  use Ecto.Migration

  def change do
    create table(:comments) do
      add :body, :text, null: false

      # Owned child — deleted with its post
      add :post_id, references(:posts, on_delete: :delete_all), null: false

      # Author — the comment survives account deletion without an author (column must be nullable)
      add :user_id, references(:users, on_delete: :nilify_all)

      timestamps(type: :utc_datetime)
    end

    create index(:comments, [:post_id])
    create index(:comments, [:user_id])
  end
end
on_deleteDeleting the parent…Use for
:delete_alldeletes the childrenOwned children: line items, ingredients, replies
:nilify_allsets the FK to NULL (column must allow it)Keep the child, drop the link: author, team
:restrictfails while children existParents that must be emptied first: a category with posts
:nothing (default)also fails while children exist (NO ACTION, checked at statement end)Rarely what you want — it does not "keep" the children

To make a blocked delete a form error instead of an Ecto.ConstraintError, declare it on the parent's delete changeset:

def delete_category(%Scope{} = scope, %Category{} = category) do
  true = category.user_id == scope.user.id

  category
  |> Ecto.Changeset.change()
  |> Ecto.Changeset.no_assoc_constraint(:posts)
  |> Repo.delete()
end
# => {:error, changeset} with posts: "are still associated with this entry"

Foreign Key Indexes

references/2 creates the constraint but not an index. Postgres checks child rows on every parent delete, so without create index(:comments, [:post_id]) each delete scans the whole comments table.

Testing Nested Associations

Test the rollback through a step that returns an error:

describe "place_order/2" do
  test "rolls back the order when stock runs out" do
    scope = user_scope_fixture()
    product = product_fixture(stock: 1)

    assert {:error, {:reserve, 0}, :insufficient_stock, _changes} =
             Orders.place_order(scope, [%{product_id: product.id, quantity: 2}])

    assert Repo.aggregate(Order, :count) == 0
    assert Repo.reload!(product).stock == 1
  end
end

A bad foreign key in an insert_all step raises; test that with assert_raise Postgrex.Error, fn -> ... end, not by matching {:error, _, _, _}.


See the ecto-essentials skill for scoped contexts, transactions and migrations. See the ecto-changeset-patterns skill for changeset composition and validation. See the testing-essentials skill for comprehensive testing patterns.

Ecto Queries & Performance

Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14, ecto_sql 3.14 (PostgreSQL 16) — October 2026

RULES — Follow these with no exceptions

  1. Preload in the context, once for the whole list. Use preload: in the query or one Repo.preload(list, ...). Never call Repo.preload, Repo.get or a context function per row, whether in Enum.map, a HEEx :for or a JSON view.
  2. Use separate-query preloads by default. Join-preload only a belongs_to/has_one that you also filter or sort on. Joining a has_many multiplies rows, and limit then counts children instead of parents.
  3. A limit in a preload query is global, not per parent. For "latest N per post", use a row_number() window restricted to the parents' ids.
  4. Count and check without loading rows. Use Repo.aggregate(q, :count), Repo.exists?/1, group_by + count(), or select_merge into a virtual field. Never length(Repo.all(q)).
  5. Compose with named bindings and dynamic/2. Put as: on joins and use with_named_binding/3 so a join is added only once. For "has any child", use exists/1 with parent_as/1 instead of a join plus distinct.
  6. Run Repo.stream only inside Repo.transact. The function must return {:ok, _}, the transaction needs timeout: :infinity, and streams don't support preloads. For long jobs, batch by keyset (where: p.id > ^last_id), never OFFSET.
  7. Never read-modify-write a counter or balance. Use update_all(inc: ...), a conditional update_all, lock: "FOR UPDATE" inside Repo.transact, or optimistic_lock/3 with stale_error_field:.
  8. insert_all and update_all bypass changesets. Nothing is validated and no timestamps are generated. Set inserted_at/updated_at yourself, and chunk so rows × fields stays under Postgres's 65,535 parameters.
  9. Measure, then index the query you actually run. Use Repo.explain(:all, q, analyze: true) and the [:my_app, :repo, :query] telemetry. Put equality columns first in a composite index. A partial or expression index is only used when the query repeats its predicate or expression.
  10. Tenant isolation comes from the scope, passed explicitly. prepare_query/3 is only a guard that raises when the tenant option is missing. Never keep the tenant in the process dictionary.

Examples extend the Phoenix 1.8 generated Blog.Post with belongs_to :user (replacing field :user_id, :id) and has_many :comments.


Spotting N+1

The usual cause is a query hidden inside a loop: a context call in a template, a Repo.preload per element, or a JSON view that loads data for each item.

<%!-- One COUNT query per post, on every render --%>
<div :for={{id, post} <- @streams.posts} id={id}>
  {post.title} ({Blog.count_comments(@current_scope, post)} comments)
</div>
# One comments query per post
posts |> Enum.map(&Repo.preload(&1, :comments))

In dev, the repeats are easy to see in the log. The generated config/dev.exs sets stacktrace: true on the repo, so every query log line ends with ↳ Module.fun/arity, at: file:line. The same caller and the same SQL repeating with a different $1 is an N+1. To lock the fix in, assert a query count in a test (see the query-count helper).

def list_posts_with_comment_counts(%Scope{} = scope) do
  counts = from c in Comment, group_by: c.post_id, select: %{post_id: c.post_id, n: count(c.id)}

  from(p in Post,
    where: p.user_id == ^scope.user.id,
    left_join: c in subquery(counts),
    on: c.post_id == p.id,
    # comment_count is `field :comment_count, :integer, virtual: true` on Post
    select_merge: %{comment_count: coalesce(c.n, 0)},
    order_by: [desc: p.inserted_at, desc: p.id]
  )
  |> Repo.all()
end

The template then renders {post.comment_count}. If a template or JSON view needs data, the context function that feeds it has to load it.

Preloading: separate queries vs one join

# Separate queries (default): 1 for posts, then 1 per association for the whole
# list. Independent preloads run in parallel outside a transaction.
Post
|> where(user_id: ^scope.user.id)
|> preload([:user, comments: :user])
|> Repo.all()

# Already have the list? One query per association, not per post:
Repo.preload(posts, comments: :user)

# Join-preload: one query. Right for belongs_to/has_one you filter or sort on.
from(p in Post,
  as: :post,
  join: u in assoc(p, :user),
  as: :author,
  where: p.status == :published,
  order_by: [asc: u.email, desc: p.published_at],
  preload: [user: u]
)
|> Repo.all()
UseWhen
preload: [:comments] (separate query)has_many/many_to_many, paginated parents, nested preloads
join + preload: [user: u]belongs_to/has_one you also where/order_by on, so the join is needed anyway
preload: [comments: ^query]Filter or order the children (where: is_nil(c.deleted_at), order_by: c.inserted_at)
preload_order: [asc: :inserted_at] on has_manyA default child order, used when the preload query has no order_by of its own

Join-preloading a has_many with limit: from p in Post, join: c in assoc(p, :comments), preload: [comments: c], limit: 3 returns one post with three comments, because the limit applies to the joined rows. Paginate the parents, then preload the children with separate queries.

Repo.preload/3 skips associations that are already loaded. Pass force: true to reload them after a write.

Top N children per parent

A preload query's limit applies to all parents together. preload: [comments: ^from(c in Comment, limit: 2)] returns two comments in total, not two per post. Rank the children with a window function instead, and filter the ranking to the parents you already have so it doesn't scan the whole table:

def preload_latest_comments(posts, n) do
  post_ids = Enum.map(posts, & &1.id)

  ranked =
    from c in Comment,
      where: c.post_id in ^post_ids,
      select: %{id: c.id, rank: over(row_number(), :per_post)},
      windows: [per_post: [partition_by: c.post_id, order_by: [desc: c.inserted_at]]]

  latest = from c in Comment, join: r in subquery(ranked), on: c.id == r.id and r.rank <= ^n

  Repo.preload(posts, comments: latest)
end

Composable queries

Name every binding that other functions will refer to (as: :post, as: :author). Positional bindings break as soon as a join is added in a different order.

def search_posts(%Scope{} = scope, params) do
  from(p in Post, as: :post, where: p.user_id == ^scope.user.id)
  |> maybe_join_author(params)
  |> where(^post_filters(params))
  |> order_by([post: p], desc: p.inserted_at, desc: p.id)
  |> Repo.all()
end

# Allowlist of keys; anything else is ignored. dynamic/2 builds the WHERE.
# Every named binding a dynamic uses must already be joined when where/2 runs,
# otherwise it raises "unknown bind name `:author`" — so join first.
defp post_filters(params) do
  Enum.reduce(params, dynamic(true), fn
    {"status", status}, dyn when status in ~w(draft published) ->
      dynamic([post: p], ^dyn and p.status == ^status)

    {"q", term}, dyn ->
      pattern = "%" <> escape_like(term) <> "%"
      dynamic([post: p], ^dyn and (ilike(p.title, ^pattern) or ilike(p.body, ^pattern)))

    {"author_email", email}, dyn ->
      dynamic([author: a], ^dyn and a.email == ^email)

    {"commented", "true"}, dyn ->
      dynamic([post: p], ^dyn and exists(from c in Comment, where: c.post_id == parent_as(:post).id))

    _other, dyn ->
      dyn
  end)
end

defp maybe_join_author(query, %{"author_email" => _}) do
  with_named_binding(query, :author, fn query, binding ->
    join(query, :inner, [post: p], a in assoc(p, :user), as: ^binding)
  end)
end

defp maybe_join_author(query, _params), do: query
  • escape_like/1 is in the ecto-essentials skill. Unescaped % or _ in a search term match everything.
  • exists/1 takes a query directly, as in exists(from c in Comment, ...). exists(subquery(...)) also compiles. It must reference the outer row through parent_as(:post), so the outer query needs as: :post. Use not exists(...) for "posts with no comments".
  • has_named_binding?/2 returns whether a binding exists, and with_named_binding/3 adds a binding only if it is missing. The join above runs at most once, however many filters need it.
  • Use subquery/1 to aggregate first and then join, as in the comment counts above. Joining the raw children and then using group_by on the parent also works, but it can't be combined with preloads cleanly.

Counting without loading

Repo.aggregate(from(p in Post, where: p.user_id == ^scope.user.id), :count)
Repo.exists?(from c in Comment, where: c.post_id == ^post.id)

from(p in Post, where: p.user_id == ^scope.user.id, group_by: p.status, select: {p.status, count()})
|> Repo.all()
|> Map.new()
#=> %{draft: 4, published: 5}
  • count() with no argument is count(*). count(c.id) skips NULLs, which matters with a left_join.
  • Repo.aggregate/3 drops order_by and preloads, and wraps a query that has limit, offset or distinct in a subquery, so Repo.aggregate(from(p in Post, limit: 2), :count) returns 2, not the table count. It raises on a query with group_by; use the group_by + select form above.
  • Use Repo.exists?/1 for if count > 0 checks. It stops at the first matching row.

Large result sets

def export_posts(%Scope{} = scope, device) do
  query = from p in Post, where: p.user_id == ^scope.user.id, order_by: p.id

  Repo.transact(
    fn ->
      query
      |> Repo.stream(max_rows: 1_000)
      |> Stream.chunk_every(1_000)
      |> Stream.flat_map(&Repo.preload(&1, :comments))
      |> Stream.each(&IO.binwrite(device, csv_line(&1)))
      |> Stream.run()

      {:ok, :exported}
    end,
    timeout: :infinity
  )
end
  • Enumerating a stream outside a transaction raises cannot reduce stream outside of transaction.
  • Repo.transact/2 raises ArgumentError unless the function returns {:ok, _} or {:error, _}. The Repo.stream docs' own example returns Enum.to_list(stream) and would hit this error.
  • preload: on a streamed query raises preloads are not supported on streams. Chunk the stream and call Repo.preload/2 per chunk, as above.
  • max_rows defaults to 500. The transaction's default 15 s timeout applies to the whole stream, so pass timeout: :infinity, or a real limit.
  • A long-lived transaction holds a snapshot, which blocks vacuum and keeps locks. For backfills and jobs, process keyset batches, each in its own short query:
def touch_all_posts(last_id \\ 0) do
  ids = Repo.all(from p in Post, where: p.id > ^last_id, order_by: p.id, limit: 1_000, select: p.id)

  case ids do
    [] ->
      :done

    ids ->
      now = DateTime.utc_now(:second)
      Repo.update_all(from(p in Post, where: p.id in ^ids), set: [updated_at: now])
      touch_all_posts(List.last(ids))
  end
end

OFFSET n makes Postgres read and discard n rows on every page, and rows that change between pages are skipped or repeated. Keyset pagination for UIs and APIs, with an (inserted_at, id) cursor, is covered in the phoenix-json-api skill. Run backfills outside migrations; see the ecto-migrations-safety skill.

Concurrency and correctness

Counters: one atomic statement. Reading a value, adding to it in Elixir and writing it back loses updates under concurrency.

from(p in Post, where: p.id == ^post.id)
|> Repo.update_all(inc: [comments_count: 1], set: [updated_at: DateTime.utc_now(:second)])
# UPDATE posts SET comments_count = comments_count + 1, updated_at = $1 WHERE id = $2

Counter cache with prepare_changes/2. The function runs inside the insert's transaction, and only when the changeset is valid:

def create_comment(%Scope{} = scope, %Post{} = post, attrs) do
  post
  |> Ecto.build_assoc(:comments)
  |> Comment.changeset(attrs, scope)
  |> Ecto.Changeset.prepare_changes(fn changeset ->
    post_id = Ecto.Changeset.get_field(changeset, :post_id)
    changeset.repo.update_all(from(p in Post, where: p.id == ^post_id), inc: [comments_count: 1])
    changeset
  end)
  |> Repo.insert()
end

post must come from a scoped lookup (get_post!(scope, id), or whatever posts this user may comment on). Never cast post_id.

Conditional update when the rule involves a single row: the WHERE enforces it atomically, without a lock.

{count, _} =
  from(w in Wallet, where: w.id == ^wallet.id and w.balance >= ^amount)
  |> Repo.update_all(inc: [balance: -amount])

if count == 1, do: :ok, else: {:error, :insufficient_funds}

FOR UPDATE when the decision needs application logic across reads. The lock only lasts as long as the transaction:

def transfer(%Scope{} = scope, from_id, to_id, amount) do
  Repo.transact(fn ->
    # One statement ordered by id: concurrent transfers lock rows in the same order
    wallets =
      from(w in Wallet, where: w.id in ^[from_id, to_id], order_by: w.id, lock: "FOR UPDATE")
      |> Repo.all()
      |> Map.new(&{&1.id, &1})

    from_wallet = Map.fetch!(wallets, from_id)
    to_wallet = Map.fetch!(wallets, to_id)
    true = from_wallet.user_id == scope.user.id

    # check_limits/2 returns :ok or {:error, reason}; any {:error, _} rolls back
    with :ok <- check_limits(from_wallet, amount),
         {:ok, _} <- Repo.update(Wallet.debit_changeset(from_wallet, amount)),
         {:ok, _} <- Repo.update(Wallet.credit_changeset(to_wallet, amount)) do
      {:ok, :transferred}
    end
  end)
end

Two transactions that lock the same rows in different orders deadlock, so lock them in one ordered statement as above (or always in id order).

FOR UPDATE SKIP LOCKED lets workers claim rows without blocking each other: from(j in Job, where: j.state == "available", order_by: j.id, limit: 10, lock: "FOR UPDATE SKIP LOCKED") inside Repo.transact. For background jobs, use Oban (see the oban-essentials skill) rather than building your own queue.

Optimistic locking for records edited in forms, where two users saving the same post must not silently overwrite each other. Add add :lock_version, :integer, default: 1, null: false to the table and field :lock_version, :integer, default: 1 to the schema:

def update_post(%Scope{} = scope, %Post{} = post, attrs) do
  true = post.user_id == scope.user.id

  post
  |> Post.changeset(attrs, scope)
  |> Ecto.Changeset.optimistic_lock(:lock_version)
  |> Repo.update(stale_error_field: :lock_version)
end
  • Without stale_error_field:, a stale update raises Ecto.StaleEntryError. With it, the update returns {:error, changeset} with lock_version: {"is stale", [stale: true]}. The field has no input, so show that error in a flash ("changed by someone else — reload").
  • The version comes from the struct you pass in. A LiveView keeps the post it loaded in mount, which is the right version. After a successful save, keep the returned post, which has the incremented version.

Bulk writes with insert_all

# Migration: create unique_index(:posts, [:user_id, :slug])
def import_posts(%Scope{} = scope, rows) do
  now = DateTime.utc_now(:second)

  entries =
    Enum.map(rows, fn row ->
      %{
        title: row.title,
        body: row.body,
        slug: row.slug,
        user_id: {:placeholder, :user_id},
        inserted_at: {:placeholder, :now},
        updated_at: {:placeholder, :now}
      }
    end)

  Repo.transact(fn ->
    total =
      entries
      |> Enum.chunk_every(5_000)
      |> Enum.reduce(0, fn chunk, acc ->
        {count, _} =
          Repo.insert_all(Post, chunk,
            placeholders: %{now: now, user_id: scope.user.id},
            on_conflict: {:replace, [:title, :body, :updated_at]},
            conflict_target: [:user_id, :slug]
          )

        acc + count
      end)

    {:ok, total}
  end)
end
  • No timestamps. insert_all doesn't autogenerate inserted_at/updated_at, or any field except an :id/:binary_id primary key. With null: false columns, leaving them out fails with not_null_violation.
  • No changesets. Values are dumped to their types, but nothing is validated. Validate user-supplied rows first, for example with a changeset and apply_action/2, and set user_id from the scope, never from the row.
  • 65,535 bind parameters per statement. Going over raises postgresql protocol can not handle N parameters. Each placeholder is sent once, whatever the number of rows, so chunk by div(65_535, fields_not_in_placeholders). Smaller chunks (1k–5k rows) keep locks and memory reasonable.
  • returning: returns structs for the rows written. With on_conflict: :nothing, skipped rows are not returned. With {:replace, fields}, updated rows are returned too.
  • conflict_target must match a unique index exactly. Never include the conflict-target columns in {:replace, ...}. Upserts through a changeset (Repo.insert/2) are covered in the ecto-essentials skill.

Measuring

query = from p in Post, where: p.user_id == ^user_id and is_nil(p.deleted_at), order_by: [desc: p.published_at]

Repo.explain(:all, query, analyze: true, buffers: true) |> IO.puts()
# Index Scan Backward using posts_user_id_published_at_index on posts p0 ...

Repo.to_sql(:all, query)
#=> {"SELECT ... WHERE ((p0.\"user_id\" = $1) AND (p0.\"deleted_at\" IS NULL)) ...", [42]}
  • Repo.explain/3 is the same as Ecto.Adapters.SQL.explain(Repo, ...). It takes :all, :update_all or :delete_all, and the Postgres options analyze, verbose, costs, settings, buffers, timing, summary, format (:text, :map, :yaml) and plan.
  • analyze: true executes the query. By default it runs inside a transaction that is rolled back, so analyzing update_all is safe. Inside your own Repo.transact, that forced rollback aborts your transaction. Pass wrap_in_transaction: false there. The result then comes back as {:ok, plan}.
  • Run EXPLAIN against production-sized data. On a dev table with ten rows, Postgres picks a sequential scan regardless of your indexes.
  • In production, watch [:my_app, :repo, :query] telemetry (total_time, queue_time) for slow queries and pool pressure; see the telemetry-essentials skill. For copy-pasteable SQL with inlined params in dev, the ecto_dev_logger package replaces the default logger: set log: false on the repo in dev and call Ecto.DevLogger.install(MyApp.Repo).

Indexes for the queries you run

Query shapeIndex
where user_id = ? order by published_at descindex(:posts, [:user_id, :published_at]): equality columns first, then the sort or range column
Same, plus is_nil(p.deleted_at) on every readindex(:posts, [:user_id, :published_at], where: "deleted_at IS NULL"): smaller, and only used when the query includes deleted_at IS NULL
where state = 'available' on a mostly-processed tableindex(:jobs, [:inserted_at], where: "state = 'available'")
fragment("lower(?)", u.email) == ^String.downcase(email)index(:users, ["(lower(email))"], name: :users_lower_email_index): the query must use the same expression (or use citext)
Keyset (inserted_at, id) cursorindex(:posts, [:user_id, :inserted_at, :id])

A composite index on [:user_id, :published_at] also serves queries on user_id alone, but not queries on published_at alone. Every foreign key needs its own index (or must lead a composite one) for joins and on_delete. Add indexes to large tables with concurrently: true; see the ecto-migrations-safety skill, and the ecto-essentials skill for basic index and constraint syntax.

Multi-tenancy

Row-level tenancy (an org_id column) is what Phoenix 1.8 scopes are for. Context functions take the scope and filter explicitly, as in the ecto-essentials skill. A repo prepare_query/3 callback can add a guard, so a forgotten filter raises instead of leaking. The callback is prepare_query(operation, query, opts) and returns {query, opts}. It raises when a schema with an org_id field is queried without org_id:, and adds where(org_id: ^org_id) when the option is given. Contexts then call Repo.all(query, org_id: scope.org.id). Full code and a coverage table are in the guard reference.

  • It runs for all/get/one/aggregate/exists?/stream/update_all/delete_all, but not for insert, update or delete of a struct. Writes still need the scope check.
  • Options reach preload queries, so preloaded tenant tables are filtered too. Joins, subquery sources and bare table strings are not filtered.
  • Migrations query with schema_migration: true, so the guard must let those through.
  • Take the tenant from scope and pass it as an option. Don't store it in the process dictionary for default_options/1 to read: it is invisible in the code, and it is lost in parallel preloads, Tasks and LiveView assign_async, which all run in other processes.

Schema-per-tenant (Postgres schemas) is covered in the multi-tenancy reference: prefix: and put_query_prefix/2 at runtime, and @schema_prefix only for fixed schemas.

Testing

When writing tests for query performance (query counts, lock behavior), invoke elixir-phoenix-guide:testing-essentials before writing any _test.exs file. The query-count helper is in the reference.

Elixir Essentials

Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14 — October 2026

Not for: OTP, Ecto, LiveView, tests — use the specific skill (otp-essentials, ecto-essentials, phoenix-liveview-essentials, testing-essentials).

Phoenix project layout: see project-structure.md.

RULES — Follow these with no exceptions

  1. Branch with multi-clause functions, pattern matching and case — never nest if; unless is soft-deprecated, write if !cond
  2. A fallible function returns {:ok, value} | {:error, reason} on every path — never a bare value from one clause and a tuple from another
  3. Error reasons are atoms (or a changeset), not strings — translate them to messages at the edge (controller, LiveView)
  4. End a with on the last call itself, and no catch-all else — {:ok, x} <- f() do {:ok, x} end is redundant (Credo RedundantWithClauseResult)
  5. Multi-step writes go inside Repo.transact/2 — a with alone does not roll back the first write when a later step fails
  6. Call ! functions only when failure is a bug — never wrap a bang call in try/rescue; call the non-bang version and case on it
  7. A struct pattern matches nil fields — %User{name: name} binds nil; add when is_binary(name) when you rely on the value
  8. Treat compiler type warnings as bugs — fix the code; don't add guards or _ = just to silence them
  9. Logging: put values you'll filter on in Logger metadata; a human-readable message may interpolate — every module that logs has require Logger
  10. @impl true on every callback, clauses of one function grouped together — split clauses fail --warnings-as-errors, and so does a callback without @impl once another callback has one

Return shapes

# Mixed shapes: callers can't pattern match on the result
def calculate(x) when is_integer(x) and x > 0, do: x * 2
def calculate(_), do: {:error, :invalid_input}
def calculate(x) when is_integer(x) and x > 0, do: {:ok, x * 2}
def calculate(_), do: {:error, :invalid_input}

@doc """
Fetches a post owned by the scope's user. Returns `{:ok, post}` or `{:error, :not_found}`.
"""
def fetch_post(%Scope{} = scope, id) do
  case Repo.get_by(Post, id: id, user_id: scope.user.id) do
    nil -> {:error, :not_found}
    post -> {:ok, post}
  end
end

If invalid input can only come from a bug, drop the fallback clause and let FunctionClauseError crash.

with

with {:ok, attrs} <- validate(params),
     {:ok, post} <- Blog.create_post(scope, attrs) do
  {:ok, post}
end
with {:ok, attrs} <- validate(params) do
  Blog.create_post(scope, attrs)
end

Writes that must succeed or fail together run in one transaction, return atom reasons, and let every error fall through unchanged:

def transfer(%Scope{} = scope, from_id, to_id, amount) do
  Repo.transact(fn ->
    with {:ok, from} <- fetch_own_account(scope, from_id),
         {:ok, to} <- fetch_account(to_id),
         :ok <- ensure_funds(from, amount),
         {:ok, _from} <- debit(from, amount),
         {:ok, _to} <- credit(to, amount) do
      {:ok, :transferred}
    end
  end)
end
# => {:ok, :transferred} | {:error, :not_found | :insufficient_funds | Ecto.Changeset.t()}

A catch-all else error -> {:error, "failed: #{inspect(error)}"} hides new error shapes and turns them into strings nobody can match on. Add an else only to translate specific reasons, and list each one. (Row locking for the balance check: see the ecto-essentials skill.)

Bang functions and exceptions

def parse(body) do
  try do
    {:ok, Jason.decode!(body)}
  rescue
    Jason.DecodeError -> {:error, :invalid_json}
  end
end
def parse(body) do
  case JSON.decode(body) do
    {:ok, %{"id" => id}} -> {:ok, id}
    {:ok, _other} -> {:error, :missing_id}
    {:error, _reason} -> {:error, :invalid_json}
  end
end
  • Repo.get_by!/2 / get_post!/2 are right when a missing record should 404: phoenix_ecto maps Ecto.NoResultsError to a 404 page. Use the non-bang version plus case when absence is a normal outcome.
  • Reserve try/rescue for code you don't control that only raises (no tuple-returning variant exists).

Pattern-matching traps

  • %{} matches any map, not an empty one; use map_size(m) == 0.
  • Params and decoded JSON have string keys: match %{"id" => id}. Never String.to_atom/1 on input (atoms are never garbage collected); map strings to atoms explicitly or use String.to_existing_atom/1.
  • map.key raises KeyError when the key is missing; map[:key] returns nil. Structs don't implement Access, so use struct.key.
  • ==, < and > on DateTime, Date, Decimal compare struct fields, not values. Use DateTime.compare/2, Date.before?/2, Decimal.compare/2.
def display_name(%User{name: name}) when is_binary(name), do: name
def display_name(%User{email: email}), do: email

Enum pipelines and for

A 2–3 step Enum pipeline is idiomatic. A for comprehension is an alternative when you want a single pass, filters, or into:/reduce::

for item <- items, transformed = transform(item), valid?(transformed), do: format(transformed)

Logging

defmodule MyApp.Uploads do
  require Logger

  def process_upload(%Scope{} = scope, file) do
    case save_file(file) do
      {:ok, path} ->
        create_record(scope, path)

      {:error, reason} = error ->
        Logger.warning("upload failed: #{inspect(reason)}", user_id: scope.user.id)
        error
    end
  end
end

user_id goes in metadata so log search can filter on it. Phoenix's Plug.RequestId already sets request_id metadata on every request. A custom key only shows up in the output once the formatter lists it: the generated config :logger, :default_formatter, metadata: [:request_id] needs :user_id added (see the telemetry-essentials skill).

Modern Elixir (1.18+)

  • Type checker. 1.18 type-checks patterns and calls; 1.20 infers types from whole function bodies and guards, narrows types across case/cond/with clauses, and warns on redundant clauses. A type warning is a proven bug or dead code: fix the code. Keep mix compile --warnings-as-errors in CI.
  • dbg/1 prints each step of a pipeline with its result. Remove before committing (Credo's default Warning.Dbg check flags it).
  • then/2 pipes into a non-first argument; tap/2 runs a side effect and passes the value through:
    params |> normalize_attrs() |> then(&Blog.create_post(scope, &1)) |> tap(&log_result/1)
    
  • JSON (stdlib, 1.18+): JSON.decode/1 returns {:ok, term} | {:error, reason}, JSON.encode!/1. Phoenix 1.8 still generates Jason (config :phoenix, :json_library, Jason, also Phoenix's default). For structs rendered by json/2 or channels, implement the configured library's protocol (@derive {Jason.Encoder, only: [...]}); @derive JSON.Encoder alone isn't used by Phoenix. Plain decoding can use either.
  • mix format --migrate rewrites deprecated forms (unless → if !, 'abc' → ~c"abc", bitstring modifiers, and since 1.19 parens on piped calls). Run it in its own commit.
  • Structs: @enforce_keys [:id] before defstruct turns a missing key into a compile error. Write @spec on public functions for docs and Dialyzer; the 1.20 checker infers types without them.
  • defguard makes a reusable guard: defguard is_amount(x) when is_integer(x) and x > 0.
  • Process.set_label/1 (1.17+) names a Task or spawned process in Observer and crash logs: Process.set_label({:import, import_id}).
  • to_timeout/1 (1.17+): to_timeout(minute: 5) instead of 5 * 60 * 1000.

HTTP Clients with Req

Verified against Elixir 1.20, Phoenix 1.8, Req 0.7, Finch 0.24 — October 2026

RULES — Follow these with no exceptions

  1. One client module per external API. Build the %Req.Request{} in a private function from runtime config (Application.fetch_env!/2), never in a module attribute. Merge test-only options (plug:) from config, and return domain values ({:ok, celsius}), not %Req.Response{}.
  2. Match every outcome of Req.request/2: each status you expect, a catch-all {:ok, %Req.Response{status: status}}, and {:error, exception}. 4xx/5xx responses arrive as {:ok, response}, and Req.get!/2 doesn't raise on them either. Use bang functions only where a crash is fine (scripts, seeds, mix tasks).
  3. Know the default retry. retry: :safe_transient retries GET/HEAD up to 3 times on 408/429/500/502/503/504 and on transport timeouts or refused/closed connections. It sleeps in the calling process and obeys Retry-After with no upper limit. Cap that delay, and lower max_retries on user-facing paths.
  4. retry: false inside Oban workers. Oban already retries the job with backoff; Req retries on top multiply the attempts and hold the queue slot while they sleep.
  5. Retry POST/PUT/PATCH only with an idempotency key built from the business record ("order-#{id}-charge"), so it stays the same across Req retries and Oban attempts. Then retry: :transient is safe.
  6. Set every timeout on purpose. Connect (5 s by default), receive_timeout (15 s per read), request_timeout (total time, new in 0.7), and finch: [pool_timeout: ...]. Never block a LiveView event handler on a slow API: use start_async.
  7. Expect bodies of any shape. json: encodes with Jason. Responses are decoded by content-type into maps with string keys. A malformed JSON body is {:error, %Jason.DecodeError{}}, and an HTML error page from a proxy stays a binary.
  8. Never fetch a user-supplied URL without a host allowlist and redirect: false. On a redirect to another host, Req drops only authorization, so custom API-key headers go along. Never log request headers or bodies, and never use verify: :verify_none.
  9. Test with plug: {Req.Test, MyApp.Client} and retry: false in config/test.exs. Use Mox only at a behaviour boundary, when callers shouldn't see HTTP at all.
  10. Use a named Finch pool only for pool needs (size, HTTP/2, per-host config). Pass it as finch: [name: MyApp.Finch] (the 0.7 form) and put connect options in the pool config: combining finch: with connect_options: raises.

The client module

defmodule MyApp.Weather do
  @moduledoc "Client for the Example Weather API."

  @doc "Current temperature in °C. `opts` are extra Req options, e.g. `retry: false` in Oban workers."
  def current(city, opts \\ []) when is_binary(city) do
    case Req.request(new(), [url: "/v1/current", params: [city: city]] ++ opts) do
      {:ok, %Req.Response{status: 200, body: %{"celsius" => celsius}}} -> {:ok, celsius}
      {:ok, %Req.Response{status: 404}} -> {:error, :not_found}
      {:ok, %Req.Response{status: 429}} -> {:error, :rate_limited}
      {:ok, %Req.Response{status: status}} -> {:error, {:unexpected_response, status}}
      {:error, exception} -> {:error, exception}
    end
  end

  defp new do
    config = Application.fetch_env!(:my_app, __MODULE__)

    Req.new(
      base_url: Keyword.fetch!(config, :base_url),
      auth: {:bearer, Keyword.fetch!(config, :api_key)},
      receive_timeout: 5_000,
      max_retries: 2
    )
    |> Req.merge(Keyword.get(config, :req_options, []))
  end
end
# config/config.exs
config :my_app, MyApp.Weather, base_url: "https://api.weather.example"

# config/runtime.exs: secrets are read at boot, not at compile time
if config_env() == :prod do
  config :my_app, MyApp.Weather, api_key: System.fetch_env!("WEATHER_API_KEY")
end

# config/test.exs
config :my_app, MyApp.Weather,
  api_key: "test-key",
  req_options: [plug: {Req.Test, MyApp.Weather}, retry: false]
  • Build the struct per call. It's cheap and does no I/O; connections live in Finch pools and are reused. A module attribute would be evaluated at compile time, before runtime.exs runs.
  • Option names are validated. Req.new(bas_url: ...) raises ArgumentError ("Did you mean :base_url?"). Custom options need Req.Request.register_options/2 (see the reference).
  • Merging: Req.merge/2 and per-call options merge headers and params and override everything else. Options passed later win, so a caller's retry: false beats the client default.
  • The {:error, exception} side is usually %Req.TransportError{reason: :timeout | :econnrefused | :closed | ...}, but can also be %Req.HTTPError{}, %Req.TooManyRedirectsError{} or %Jason.DecodeError{}.
  • Rotating tokens: auth: fn -> {:bearer, MyApp.Tokens.fetch!()} end is evaluated on every attempt. So is {mod, fun, args}.
  • Version check: Phoenix 1.8 generates {:req, "~> 0.5"}. A fresh mix deps.get resolves that to 0.7.x, but an older mix.lock may still pin 0.5. Several options changed; see Upgrading from 0.5.

Retries

retry: :safe_transient (default)
MethodsGET, HEAD (:transient retries every method)
Responses408, 429, 500, 502, 503, 504
ExceptionsReq.TransportError with :timeout, :econnrefused, :closed; HTTP/2 :unprocessed, :pool_not_available
Attemptsmax_retries: 3, so up to 4 requests in total
Delayexponential with jitter (~1 s, 2 s, 4 s); on 429/503 the Retry-After value (seconds or HTTP date), with no cap
  • The delay is a Process.sleep/1 in the caller. A Retry-After: 3600 freezes a controller request or a LiveView for an hour.
  • Setting retry_delay makes Req ignore Retry-After (changed in 0.7). To keep honouring the header with a ceiling, pass a 2-arity retry function that returns {:delay, ms}.
  • Retries log at :warning by default. Use retry_log_level: false to silence them, or :debug.
# In the client: Req.new(..., retry: &retry?/2)
# Same policy as :safe_transient, but caps Retry-After at 5 s
defp retry?(%Req.Request{method: method}, response_or_exception) when method in [:get, :head] do
  case response_or_exception do
    %Req.Response{status: status} = response when status in [429, 503] ->
      {:delay, min(Req.Response.get_retry_after(response) || 1_000, 5_000)}

    %Req.Response{status: status} ->
      status in [408, 500, 502, 504]

    %Req.TransportError{reason: reason} ->
      reason in [:timeout, :econnrefused, :closed]

    _other ->
      false
  end
end

defp retry?(_request, _response_or_exception), do: false

Req.Response.get_retry_after/1 returns milliseconds, even though its docs say seconds. A function that returns {:delay, ms} raises if retry_delay is also set; returning true uses the default backoff.

Inside Oban workers

@impl Oban.Worker
def perform(%Oban.Job{args: %{"city" => city}}) do
  case MyApp.Weather.current(city, retry: false) do
    {:ok, celsius} -> MyApp.Forecasts.record_reading(city, celsius)
    {:error, :not_found} -> {:cancel, :unknown_city}
    {:error, reason} -> {:error, reason}
  end
end

Oban backs off between attempts and keeps the job's history. Snoozing on 429 and timeout/1 are covered in the oban-essentials skill.

POSTs and idempotency keys

def create_charge(%Order{id: order_id, total_cents: cents}, opts \\ []) do
  request_opts = [
    url: "/v1/charges",
    json: %{amount: cents, currency: "eur", reference: order_id},
    # Same key on every attempt, including Oban retries
    headers: [{"idempotency-key", "order-#{order_id}-charge"}]
  ]

  case Req.post(new(), Keyword.merge(request_opts, opts)) do
    {:ok, %Req.Response{status: status, body: %{"id" => charge_id}}} when status in [200, 201] ->
      {:ok, charge_id}

    {:ok, %Req.Response{status: 422, body: %{"error" => message}}} ->
      {:error, {:rejected, message}}

    {:ok, %Req.Response{status: status}} ->
      {:error, {:unexpected_response, status}}

    {:error, exception} ->
      {:error, exception}
  end
end

# new/0 for this API sets `retry: :transient`, safe only because every request carries a key
  • A timeout doesn't mean the server didn't act. Without a key, retrying a POST can charge twice.
  • Never generate the key inside a Req step. Req re-runs every request step on each retry, so a fresh UUID there changes between attempts. If the record has no natural id, generate the key once and store it on the row before the first attempt.
  • The header name and semantics come from the provider (Stripe-style Idempotency-Key is common). Check how long they keep keys.

Timeouts

OptionDefaultBounds
connect_options: [timeout: ms]5_000 (Finch's default; Req's docs say 30 s)TCP + TLS connect
receive_timeout: ms15_000each socket read; a slow trickle can run far longer in total
request_timeout: ms (0.7):infinitythe whole response; HTTP/1 only, best effort
finch: [pool_timeout: ms]5_000waiting for a free pool connection (top-level pool_timeout: is deprecated in 0.7)
  • The worst case is (max_retries + 1) attempts × these timeouts, plus the backoff sleeps. With the defaults, a single Req.get can take over a minute.
  • On user-facing paths, set tight values and few retries. In LiveView, run the call in start_async/3 or assign_async/3 (see the phoenix-liveview-essentials skill).
  • Each distinct connect_options value starts its own Finch pool, and Req never stops it. Keep the value constant per client, never computed per request.

JSON bodies

  • Encoding: json: data calls Jason.encode_to_iodata!/1 and sets content-type and accept to application/json. Req 0.7 depends on Jason, not Elixir's JSON module: @derive JSON.Encoder doesn't help, and a struct needs Jason.Encoder or raises Protocol.UndefinedError. Build plain maps.
  • Decoding: the default decoders: [:json, :json_api] picks the decoder from the response content-type and uses Jason.decode/1, which gives string keys. Any other type (text/html, text/plain) stays a binary. Match on status first, and never assume an error body is a map.
  • Bad JSON fails the whole call: a JSON content-type with an invalid body returns {:error, %Jason.DecodeError{}}, even for a 200.
  • decode_body: false (or decoders: false, or raw: true) keeps the body as a binary. Use it when verifying a signature over the raw bytes or decoding yourself. decoders: [json: &Jason.decode(&1, keys: :atoms)] replaces the deprecated decode_json: option.
  • Since 0.6, zip/tar/gz/csv bodies are no longer decoded automatically (decompression bombs). Opt in per format with decoders: [:json, :zip], and only for trusted hosts. Compression is opt-in too: compressed: true.

Security

  • SSRF: a URL from a user, a webhook config or job args can point at 169.254.169.254 or internal services. Check scheme and host against an allowlist, then request with redirect: false; a redirect is a new, unchecked URL. The full pattern, including DNS-rebinding notes, is in the security-essentials skill.
  • Redirects and credentials: when a redirect changes host, scheme or port, Req removes the authorization header and the :auth option (unless redirect_trusted: true). Custom headers such as x-api-key are forwarded. For APIs authenticated that way, use redirect: false or check the location yourself.
  • Logging: inspect(%Req.Request{}) masks authorization and :auth, but not other headers, and nothing masks bodies. Log the API name, the status and Exception.message/1, never resp.body or req.headers:
require Logger

Logger.warning("weather API call failed: #{Exception.message(exception)}",
  api: :weather,
  reason: inspect(exception.__struct__)
)
  • TLS: never use connect_options: [transport_opts: [verify: :verify_none]] outside local experiments. For a private CA, use transport_opts: [cacertfile: path].
  • Logger metadata conventions and filtering are in the telemetry-essentials skill.

Finch pools

By default Req uses its own Finch instance: an HTTP/1 pool of up to 50 connections per {scheme, host, port}, never terminated. Start a named pool when you need:

  • more than 50 concurrent connections to one host, or a smaller cap to protect a fragile partner;
  • HTTP/2 multiplexing (protocols: [:http2]);
  • per-host settings (connect timeout, proxy, certificates), idle-pool cleanup (pool_max_idle_time), or pool metrics (start_pool_metrics?: true).
# lib/my_app/application.ex, in children
{Finch,
 name: MyApp.Finch,
 pools: %{
   :default => [size: 50, conn_opts: [transport_opts: [timeout: 5_000]]],
   "https://api.payments.example" => [size: 10, count: 2]
 }}

# In the client
Req.new(base_url: base_url, finch: [name: MyApp.Finch, pool_timeout: 2_000])
  • finch: [name: ...] with connect_options: raises "cannot set both :finch and :connect_options". Put connect settings in the pool's conn_opts.
  • finch: [name: MyApp.Finch, size: 5] raises too: pool options belong where the pool is started.
  • The 0.5 form finch: MyApp.Finch still works but prints a deprecation warning.
  • With plug: in test config, Req uses the Req.Plug adapter and ignores Finch options, so tests don't need the pool.

Testing

The testing-essentials skill covers Req.Test.stub/2, expect/3, json/2, transport_error/2 and verify_on_exit!. What matters most for a client:

defmodule MyApp.PaymentsTest do
  use ExUnit.Case, async: true

  setup {Req.Test, :verify_on_exit!}

  test "posts the charge and keeps the idempotency key across retries" do
    test_pid = self()

    Req.Test.expect(MyApp.Payments, fn conn ->
      send(test_pid, {:key, Plug.Conn.get_req_header(conn, "idempotency-key")})
      Plug.Conn.send_resp(conn, 503, "")
    end)

    Req.Test.expect(MyApp.Payments, fn conn ->
      send(test_pid, {:key, Plug.Conn.get_req_header(conn, "idempotency-key")})
      assert conn.method == "POST"
      assert conn.body_params == %{"amount" => 1999, "currency" => "eur", "reference" => 42}
      conn |> Plug.Conn.put_status(201) |> Req.Test.json(%{"id" => "ch_1"})
    end)

    # Config has retry: false; re-enable it for this call, without the sleeps
    assert {:ok, "ch_1"} =
             MyApp.Payments.create_charge(%MyApp.Orders.Order{id: 42, total_cents: 1999},
               retry: :transient,
               retry_delay: 0,
               retry_log_level: false
             )

    assert_receive {:key, ["order-42-charge"]}
    assert_receive {:key, ["order-42-charge"]}
  end
end
  • Assert on the outgoing request: conn.method, conn.request_path, conn.query_params, Plug.Conn.get_req_header/2, and conn.body_params. The Req.Plug adapter runs Plug.Parsers for JSON, form and multipart bodies. Use Req.Test.raw_body(conn) for the exact bytes.
  • Simulate real failures:
    • an error status with a JSON body: conn |> Plug.Conn.put_status(422) |> Req.Test.json(...);
    • rate limiting: Plug.Conn.put_resp_header(conn, "retry-after", "30") before send_resp(conn, 429, "");
    • a proxy error page: Req.Test.html(conn, "<h1>Bad gateway</h1>");
    • broken JSON: put_resp_content_type("application/json") with an invalid body;
    • network errors: Req.Test.transport_error(conn, :timeout).
  • Other processes: since 0.7, processes started by the test (Task, start_supervised!, GenServer.start) find the test's stubs automatically. Processes started by the application need Req.Test.allow(MyApp.Weather, self(), pid). If you can't get the pid, use setup {Req.Test, :set_req_test_to_shared} with async: false.
  • Mox is for callers that shouldn't know about HTTP, such as a LiveView that shows the temperature. Put a behaviour in front of the client and test the client itself with Req.Test. Wiring is in the reference.

Observability

  • Finch telemetry: [:finch, :request, :start | :stop | :exception], [:finch, :queue, ...] (pool checkout), [:finch, :connect, ...], [:finch, :send, ...], [:finch, :recv, ...], [:finch, :reused_connection]. Metadata has :name (the Finch instance) and :request (a %Finch.Request{} with host, path and method). These events fire once per attempt. Add finch_private: %{api: :weather} to the client and it shows up as meta.request.private.api.
  • One event per logical call (after retries, tagged with your API name): use a small Req plugin that adds a request step and a response/error step. It's in the reference.
  • Tracing: Req.new(...) |> OpentelemetryReq.attach() (opentelemetry_req 1.0 attaches cleanly on Req 0.7). Exporter setup is in the telemetry-essentials skill.
  • Use metric tags with few values (api, status), never the URL with ids in it.

Resilience

  • Circuit breaking: when an upstream is down, fail fast instead of tying up every caller for the full timeout. A Req plugin built on :fuse checks the fuse in a request step (Req.Request.halt/2 when blown) and melts it on 5xx and transport errors. Code is in the reference.
  • Rate limits: treat 429 as a result ({:error, :rate_limited}). In Oban, snooze for the Retry-After value. To limit your own call rate, the simplest control is the concurrency of a dedicated Oban queue. Global and distributed rate limits are Oban Pro, or a token bucket you write and own.
  • Caching: cache the decoded domain value ({:ok, celsius}), not the %Req.Response{}, in ETS or Cachex with a TTL and a key built from the request inputs. Req's own cache: true step is deprecated since 0.7.1.

Upgrading from Req 0.5

0.50.7
finch: MyFinchfinch: [name: MyFinch]
pool_timeout: msfinch: [pool_timeout: ms]
decode_json: [keys: :atoms]decoders: [json: &Jason.decode(&1, keys: :atoms)]
retry_delay: and Retry-After both applysetting retry_delay ignores Retry-After
zip/tar/gz/csv decoded automaticallyonly JSON; opt in with decoders: (0.6)
compressed responses requested by defaultcompressed: true to opt in (0.6.1)
run_finch / put_plug stepsReq.Finch / Req.Plug adapter modules
cache: truedeprecated (0.7.1)
retry delays without jitterjitter by default

Oban Essentials

Verified against Elixir 1.20, Ecto 3.14, Oban 2.24, Req 0.7 — October 2026

RULES — Follow these with no exceptions

  1. use Oban.Worker with explicit queue: and max_attempts:, and match string-keyed args in perform/1
  2. Return :ok/{:ok, value} for success, {:error, reason} to retry, {:cancel, reason} to stop for good, {:snooze, period} to re-run later — prefer tuples over raising
  3. Enqueue in the same transaction as the data the job needs — Oban.insert/2 inside Repo.transact/2, or Oban.insert/3 in an Ecto.Multi; handle the result (no Oban.insert! in app code)
  4. Make workers idempotent — a job can run more than once (retries, Lifeline rescues); record completion and send an idempotency key to external APIs
  5. Uniqueness keeps :worker in fields — omit fields (default [:args, :queue, :worker]) or use [:worker, :args]; narrow with keys:, pick a state group such as :incomplete. Oban.insert_all/2 ignores unique in OSS
  6. One config :my_app, Oban block with the 2.24 service keys — cron:, pruner:, lifeline:; always enable pruner and lifeline
  7. Args hold IDs and small JSON values only — fetch fresh data in perform/1
  8. Bound every job — timeout/1 for long work; outbound HTTP uses retry: false and a host allowlist; cap snoozes with meta["snoozed"]
  9. Test with Oban.Testing — testing: :manual, perform_job/3, assert_enqueued, drain_queue; never call perform/1 directly
  10. Workflows, Batches, global and rate limits, DynamicCron and bulk unique inserts are Oban Pro — don't write OSS code that assumes them

Worker definition

defmodule MyApp.Workers.SendWelcomeEmail do
  use Oban.Worker,
    queue: :mailers,
    max_attempts: 5,
    unique: [period: {5, :minutes}, keys: [:user_id]]

  alias MyApp.Accounts

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"user_id" => user_id}}) do
    case Accounts.get_user(user_id) do
      nil -> {:cancel, :user_not_found}
      %{welcome_sent_at: %DateTime{}} -> :ok
      user -> Accounts.deliver_welcome(user)
    end
  end
end
  • Accounts.get_user/1 is Repo.get(User, id), which you add; the generator only has get_user!/1, which would raise (and retry) for a deleted user instead of cancelling.
  • max_attempts counts the first run (5 = 1 + 4 retries). Retries back off exponentially (15 s minimum, with jitter) unless you define backoff/1.
  • args are stored as JSON: keys come back as strings, structs and tuples don't survive. Enqueue %{user_id: user.id}, never %{user: user}.
  • {:cancel, reason} replaces the deprecated {:discard, reason}.

Enqueuing

Enqueue from the context, in the transaction that writes the data. If the transaction rolls back, the job is never inserted; if it commits, the job can't run before the row exists:

# The generated register_user/1 plus the job. If you added a registration_changeset/3
# (the phoenix-auth-customization skill), insert with that instead of email_changeset/2.
def register_user(attrs) do
  Repo.transact(fn ->
    with {:ok, user} <- %User{} |> User.email_changeset(attrs) |> Repo.insert(),
         {:ok, _job} <- Oban.insert(SendWelcomeEmail.new(%{user_id: user.id})) do
      {:ok, user}
    end
  end)
end

The Ecto.Multi form, when steps are built dynamically:

Ecto.Multi.new()
|> Ecto.Multi.insert(:user, User.email_changeset(%User{}, attrs))
|> Oban.insert(:welcome_job, fn %{user: user} -> SendWelcomeEmail.new(%{user_id: user.id}) end)
|> Repo.transact()
  • Scheduling: SendReminder.new(args, scheduled_in: {1, :hour}) (scheduled_in is the documented name since 2.24; schedule_in still works) or scheduled_at: datetime.
  • Unique conflicts are not errors: Oban.insert/2 returns {:ok, %Oban.Job{conflict?: true}} for a duplicate.
  • Bulk: Oban.insert_all/2 (or Oban.insert_all(multi, :jobs, changesets)) inserts many jobs in one query and returns a list. It raises on an invalid changeset and, in OSS, skips uniqueness checks; use Oban.insert/2 per job when uniqueness matters.

Configuration (Oban 2.24)

# config/config.exs
config :my_app, Oban,
  repo: MyApp.Repo,
  queues: [default: 10, mailers: 5, imports: 2],
  cron: [
    crontab: [
      {"0 2 * * *", MyApp.Workers.NightlyCleanup},
      {"*/15 * * * *", MyApp.Workers.SyncData, args: %{source: "api"}}
    ]
  ],
  pruner: [max_age: {7, :days}],
  lifeline: [rescue_after: {30, :minutes}]

# config/test.exs: no queues or plugins run; jobs stay in the table for assertions
config :my_app, Oban, testing: :manual
  • cron:, pruner:, lifeline: and reindexer: are top-level keys since 2.24 (Oban.Plugins.Cron is now Oban.Cron, and so on). The old plugins: [...] form still works.
  • Keep the Oban config in one config call. Repeated calls deep-merge keyword lists, but a plugins: list containing one bare module (Oban.Plugins.Lifeline) isn't a keyword list, so a later plugins: replaces it and cron or pruning silently disappears.
  • Lifeline is off unless configured. Without it, jobs orphaned in executing by a node restart stay there forever. It rescues purely by time, so rescue_after must exceed your longest job's timeout/1, or it re-runs jobs that are still executing.
  • Pruner keeps oban_jobs from growing without bound; max_age accepts {7, :days}.
  • Start Oban in application.ex with {Oban, Application.fetch_env!(:my_app, Oban)}, before the Endpoint.

Timeouts and backoff

@impl Oban.Worker
def timeout(_job), do: to_timeout(minute: 2)

@impl Oban.Worker
def backoff(%Oban.Job{attempt: attempt}), do: trunc(:math.pow(2, attempt) * 10)
  • timeout/1 returns milliseconds and defaults to :infinity. A timed-out job fails with Oban.TimeoutError and is retried like any error.
  • backoff/1 returns seconds until the next attempt.

Idempotency

# Sends a duplicate email whenever the job is retried or rescued
def perform(%Oban.Job{args: %{"user_id" => user_id}}) do
  user = MyApp.Accounts.get_user!(user_id)
  MyApp.Mailer.send_welcome(user)
end

The worker above checks welcome_sent_at and Accounts.deliver_welcome/1 sets it after sending. For external APIs that support it, send an idempotency key that stays the same across retries, e.g. headers: [{"idempotency-key", "order-#{order.id}-charge"}], so a retry after a timeout can't charge twice.

Long data backfills that outgrow a migration fit a self-re-enqueuing batch worker; see the ecto-migrations-safety skill for the batching query.

Uniqueness

use Oban.Worker,
  queue: :sync,
  unique: [period: :infinity, keys: [:account_id], states: :incomplete]
  • fields defaults to [:args, :queue, :worker]. Listing [:args] alone makes jobs from different workers with the same args collide.
  • states groups (2.20+): :successful (default: everything except cancelled/discarded, so a completed job blocks duplicates for the whole period), :incomplete (available, scheduled, executing, retryable, suspended: "one at a time"), :all. A hand-written list such as [:available, :scheduled, :executing] misses :retryable, letting a duplicate in while a job waits to retry.
  • Emails and notifications: the default states with a period. Syncs and imports: states: :incomplete.

HTTP workers

defmodule MyApp.Workers.FetchFeed do
  use Oban.Worker, queue: :http, max_attempts: 10

  @allowed_hosts ~w(api.example.com feeds.example.org)
  @max_snoozes 5

  @impl Oban.Worker
  def timeout(_job), do: to_timeout(second: 30)

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"url" => url}, meta: meta}) do
    with :ok <- check_host(url) do
      case Req.get(url, retry: false, redirect: false) do
        {:ok, %Req.Response{status: 200, body: body}} -> MyApp.Feeds.import(body)
        {:ok, %Req.Response{status: status}} when status in [404, 410] -> {:cancel, {:gone, status}}
        {:ok, %Req.Response{status: 429} = resp} -> snooze(resp, meta)
        {:ok, %Req.Response{status: status}} -> {:error, {:unexpected_status, status}}
        {:error, exception} -> {:error, exception}
      end
    end
  end

  defp check_host(url) do
    case URI.parse(url) do
      %URI{scheme: "https", host: host} when host in @allowed_hosts -> :ok
      _other -> {:cancel, :host_not_allowed}
    end
  end

  defp snooze(resp, meta) do
    if Map.get(meta, "snoozed", 0) >= @max_snoozes do
      {:error, :rate_limited}
    else
      {:snooze, retry_after(resp)}
    end
  end

  defp retry_after(resp) do
    resp
    |> Req.Response.get_header("retry-after")
    |> List.first("")
    |> Integer.parse()
    |> case do
      {seconds, ""} when seconds > 0 -> min(seconds, 3600)
      _missing_or_http_date -> 60
    end
  end
end
  • SSRF: a URL from args can point at internal services or cloud metadata. Check the host against an allowlist and disable redirects (redirect: false), which could otherwise leave the allowlist.
  • retry: false: Req retries GET/HEAD requests on 408/429/500/502/503/504 and transport errors by default (3 retries, sleeping for an uncapped Retry-After), multiplying Oban's own attempts and blocking the queue slot. For the client module itself (Req options, timeouts, capping Retry-After, Req.Test wiring), see the http-clients-req skill.
  • Match every status: a case without a fallback clause raises CaseClauseError on the first unexpected status.
  • Snoozes (2.24): a snooze no longer consumes an attempt, so max_attempts can't stop a job that keeps snoozing, and attempt-based delays stay constant. Count snoozes with meta["snoozed"] and stop after a limit. {:snooze, period} accepts seconds or {5, :minutes}.

Testing

defmodule MyApp.Workers.SendWelcomeEmailTest do
  use MyApp.DataCase, async: true
  use Oban.Testing, repo: MyApp.Repo

  import MyApp.AccountsFixtures

  alias MyApp.Workers.{FetchFeed, SendWelcomeEmail}

  test "registering a user enqueues the welcome email" do
    {:ok, user} = MyApp.Accounts.register_user(valid_user_attributes())
    assert_enqueued worker: SendWelcomeEmail, args: %{user_id: user.id}
  end

  test "sends the email" do
    user = user_fixture()
    assert {:ok, _user} = perform_job(SendWelcomeEmail, %{user_id: user.id})
  end

  test "cancels for a missing user" do
    assert {:cancel, :user_not_found} = perform_job(SendWelcomeEmail, %{user_id: -1})
  end

  test "cancels URLs outside the allowlist" do
    assert {:cancel, :host_not_allowed} =
             perform_job(FetchFeed, %{url: "http://169.254.169.254/latest/meta-data"})
  end
end
  • perform_job/3 stringifies args, validates the worker's options, checks the return value, and accepts job options such as attempt: 10 or meta: %{"snoozed" => 5} to exercise last-attempt and snooze-cap branches.
  • Oban.drain_queue(queue: :mailers) runs the queue's available jobs in the test process and returns %{success: n, failure: n, ...}; add with_recursion: true when jobs enqueue jobs and with_scheduled: true to include scheduled ones.
  • Oban.Testing.with_testing_mode(:inline, fn -> ... end) runs jobs immediately inside one test; assert_enqueued can't see inline jobs because they're never inserted.
  • assert_enqueued worker: SendReminder, scheduled_in: {1, :hour} (2.24) asserts relative schedules.

Tests that reach the HTTP call need a stub: let the worker merge test-only Req options (e.g. plug: {Req.Test, MyApp.Workers.FetchFeed}) from config, and define responses with Req.Test.stub/2. See the testing-essentials skill.

Oban OSS vs Oban Pro

Available only in Oban Pro (licensed): Workflows (job dependencies, fan-out/fan-in), Batches with callbacks, the Smart Engine's global concurrency, rate limiting, queue partitioning and bulk unique insert_all, DynamicCron/DynamicQueues, Pro Lifeline. In OSS, build sequencing by enqueuing the next job at the end of perform/1, and limit concurrency with the queue's local limit.

OTP Essentials

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2 — October 2026

RULES — Follow these with no exceptions

  1. Always use @impl true before GenServer/Supervisor/Agent callbacks
  2. Keep init/1 fast — return {:ok, state, {:continue, term}} and do DB/network setup in handle_continue/2; a slow init blocks the supervisor and app boot
  3. Default to GenServer.call — it gives back-pressure and a 5 s timeout. Use cast only for cheap state updates you can afford to lose; send slow side effects (email, HTTP) to Task.Supervisor or Oban
  4. Wrap every process behind a public API module — callers never write GenServer.call(pid, ...) themselves
  5. One argument shape: start_link(opts) with a keyword list — read it with Keyword.fetch!/2; child specs pass {MyApp.Room, room_id: id}
  6. Registry for dynamic processes; atoms only for singletons — never build a name with String.to_atom/1
  7. Every long-running process is supervised — no bare spawn/Task.start; inside a LiveView use start_async/3 or assign_async/3
  8. Every Task.async is awaited — for collections use Task.Supervisor.async_stream_nolink/4 with on_timeout: :kill_task
  9. Don't rely on terminate/2 for cleanup — on supervisor shutdown it runs only if the process traps exits; use links or monitors for cleanup that must happen

GenServer

Public API

defmodule MyApp.Cache do
  use GenServer

  # --- Public API ---

  def start_link(opts) do
    GenServer.start_link(__MODULE__, opts, name: Keyword.get(opts, :name, __MODULE__))
  end

  def get(server \\ __MODULE__, key), do: GenServer.call(server, {:get, key})

  def put(server \\ __MODULE__, key, value), do: GenServer.call(server, {:put, key, value})

  # --- Callbacks ---

  @impl true
  def init(_opts), do: {:ok, %{}}

  @impl true
  def handle_call({:get, key}, _from, state), do: {:reply, Map.get(state, key), state}

  def handle_call({:put, key, value}, _from, state), do: {:reply, :ok, Map.put(state, key, value)}
end

Fast init with handle_continue

@impl true
def init(_opts) do
  items = MyApp.Repo.all(MyApp.Item)  # blocks the supervisor until the query returns
  {:ok, %{items: items}}
end
@impl true
def init(_opts), do: {:ok, %{items: []}, {:continue, :load}}

@impl true
def handle_continue(:load, state), do: {:noreply, %{state | items: MyApp.Repo.all(MyApp.Item)}}

call vs cast

  • GenServer.call/3 waits 5 000 ms by default, then exits the caller (the server keeps working and its late reply is discarded). Pass a timeout only when you know the work is slower: GenServer.call(server, msg, to_timeout(second: 30)).
  • cast returns immediately, gives no back-pressure (a flooded mailbox grows without bound), and the message is lost if the server crashes. Fine for increment; wrong for "send this email".
# Fire-and-forget through a GenServer: the email is lost if EmailServer crashes
def send_welcome(user), do: GenServer.cast(EmailServer, {:send, user})
# Work that may be lost: a supervised task. Work that must happen: an Oban job.
def send_welcome(user) do
  Task.Supervisor.start_child(MyApp.TaskSupervisor, fn -> MyApp.Mailer.deliver_welcome(user) end)
end

Deferred replies with GenServer.reply/2

Return {:noreply, state} from handle_call/3, keep from, and reply later. The server stays responsive while slow work runs elsewhere:

@impl true
def handle_call({:lookup, key}, from, state) do
  task = Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn -> slow_lookup(key) end)
  {:noreply, put_in(state.waiting[task.ref], from)}
end

@impl true
def handle_info({ref, result}, state) when is_reference(ref) do
  Process.demonitor(ref, [:flush])
  {from, waiting} = Map.pop!(state.waiting, ref)
  GenServer.reply(from, {:ok, result})
  {:noreply, %{state | waiting: waiting}}
end

def handle_info({:DOWN, ref, :process, _pid, reason}, state) do
  {from, waiting} = Map.pop!(state.waiting, ref)
  GenServer.reply(from, {:error, reason})
  {:noreply, %{state | waiting: waiting}}
end

handle_info and unexpected messages

Timers, monitors, PubSub and task replies arrive in handle_info/2. Once you define handle_info/2, an unmatched message raises FunctionClauseError; add a final clause if stray messages are possible.

require Logger

@impl true
def handle_info(:tick, state) do
  Process.send_after(self(), :tick, 1_000)
  {:noreply, %{state | count: state.count + 1}}
end

def handle_info(msg, state) do
  Logger.warning("unexpected message: #{inspect(msg)}", server: __MODULE__)
  {:noreply, state}
end

Expected vs unexpected errors

Reply with {:error, reason} for failures the caller can act on; let everything else crash so the supervisor restarts with clean state.

require Logger

@impl true
def handle_call({:charge, order_id}, _from, state) do
  case Payments.charge(order_id) do
    {:ok, receipt} ->
      {:reply, {:ok, receipt}, state}

    {:error, reason} ->
      Logger.error("charge failed: #{inspect(reason)}", order_id: order_id)
      {:reply, {:error, reason}, state}
  end
end

terminate/2

terminate/2 runs when a callback returns {:stop, ...} or raises. On supervisor shutdown it runs only if the process traps exits (Process.flag(:trap_exit, true) in init/1) and its child spec shutdown isn't :brutal_kill. It never runs on Process.exit(pid, :kill) or a VM crash. Put cleanup that must happen in another process that monitors this one.


Supervisors

Strategies and restart values

  • :one_for_one (default choice): restart only the failed child.
  • :rest_for_one: restart the failed child and every child started after it (later children depend on earlier ones).
  • :one_for_all: restart all children (they share state).
  • A supervisor gives up after 3 restarts in 5 s (max_restarts/max_seconds) and exits, escalating to its parent.

Child restart: values: :permanent (default for GenServer, always restarted), :transient (restarted only after an abnormal exit; use for processes that finish their job and stop with :normal), :temporary (never restarted; default for Task.Supervisor.start_child/3).

defmodule MyApp.Import do
  use GenServer, restart: :transient
  # stops with {:stop, :normal, state} when done; restarted only if it crashes
end

Application supervision tree

Start order follows the generated Phoenix 1.8 application.ex; your processes go before the Endpoint:

children = [
  MyAppWeb.Telemetry,
  MyApp.Repo,
  {DNSCluster, query: Application.get_env(:my_app, :dns_cluster_query) || :ignore},
  {Phoenix.PubSub, name: MyApp.PubSub},
  {Registry, keys: :unique, name: MyApp.Registry},
  {Task.Supervisor, name: MyApp.TaskSupervisor},
  {DynamicSupervisor, name: MyApp.RoomSupervisor, strategy: :one_for_one},
  MyApp.Cache,
  MyAppWeb.Endpoint
]

Dynamic children with Registry names

defmodule MyApp.Room do
  use GenServer, restart: :transient

  def start_link(opts) do
    room_id = Keyword.fetch!(opts, :room_id)
    GenServer.start_link(__MODULE__, room_id, name: via(room_id))
  end

  def start(room_id) do
    DynamicSupervisor.start_child(MyApp.RoomSupervisor, {__MODULE__, room_id: room_id})
  end

  def whereis(room_id) do
    case Registry.lookup(MyApp.Registry, {:room, room_id}) do
      [{pid, _value}] -> {:ok, pid}
      [] -> {:error, :not_found}
    end
  end

  defp via(room_id), do: {:via, Registry, {MyApp.Registry, {:room, room_id}}}

  @impl true
  def init(room_id), do: {:ok, %{room_id: room_id, members: MapSet.new()}}
end

DynamicSupervisor.start_child/2 returns {:error, {:already_started, pid}} when the name is taken; treat that as success if you only need the pid.

PartitionSupervisor for a bottleneck supervisor

One DynamicSupervisor (or one GenServer) serialises every start_child. PartitionSupervisor (1.14+) runs one copy per scheduler and routes by key:

# application.ex
{PartitionSupervisor, child_spec: DynamicSupervisor, name: MyApp.RoomSupervisors}

# starting a room
DynamicSupervisor.start_child(
  {:via, PartitionSupervisor, {MyApp.RoomSupervisors, room_id}},
  {MyApp.Room, room_id: room_id}
)

Tasks

# Concurrent work you wait for, with an explicit timeout
profile = Task.async(fn -> fetch_profile(user_id) end)
posts = Task.async(fn -> fetch_posts(user_id) end)
{Task.await(profile, 5_000), Task.await(posts, 5_000)}

# A collection: bounded concurrency, slow items killed, crashes don't take the caller down
MyApp.TaskSupervisor
|> Task.Supervisor.async_stream_nolink(urls, &fetch/1,
  max_concurrency: 8,
  timeout: 10_000,
  on_timeout: :kill_task
)
|> Enum.flat_map(fn
  {:ok, result} -> [result]
  {:exit, _reason} -> []
end)
  • Task.async/1 links the task to the caller: if the task crashes, so does the caller. Use Task.Supervisor.async_nolink/2 when the caller must survive.
  • Plain Task.async_stream/3 defaults to on_timeout: :exit, which crashes the caller on the first slow item.
  • In a LiveView, use start_async/3 + handle_async/3 (or assign_async/3), never Task.async: LiveView supervises the task, cancels it when the user leaves, and turns crashes into {:exit, reason}. See the phoenix-liveview-essentials skill.

Agent

Use an Agent only for trivial get/update state. Anything needing handle_info, timeouts or multi-step logic is a GenServer.

defmodule MyApp.Counter do
  use Agent

  def start_link(opts) do
    Agent.start_link(fn -> 0 end, name: Keyword.get(opts, :name, __MODULE__))
  end

  def value(counter \\ __MODULE__), do: Agent.get(counter, & &1)

  def increment(counter \\ __MODULE__), do: Agent.update(counter, &(&1 + 1))
end

Process naming

  • Singletons: name: __MODULE__.
  • One process per entity (room, user, game): a {:via, Registry, {MyApp.Registry, key}} name, as in MyApp.Room above.
  • Never String.to_atom("room_#{id}"): atoms are never garbage collected and the atom table has a fixed limit.

Links vs monitors

Process.link/1 is bidirectional (crashes propagate; that's what supervisors use). Process.monitor/1 is one-way: the watcher gets {:DOWN, ref, :process, pid, reason} in handle_info/2 and keeps running. Use monitors to observe processes you don't own.

ETS for read-heavy shared state

The owner process creates the table and is the only writer; every other process reads directly. The default access is :protected (owner writes, all read), so don't pass :public unless other processes must write.

@impl true
def init(_opts) do
  :ets.new(:my_cache, [:named_table, :set, read_concurrency: true])
  {:ok, %{}}
end

# Readers (any process): no GenServer round trip
def lookup(key) do
  case :ets.lookup(:my_cache, key) do
    [{^key, value}] -> {:ok, value}
    [] -> :error
  end
end

# Writers go through the owner
def put(key, value), do: GenServer.call(__MODULE__, {:put, key, value})

@impl true
def handle_call({:put, key, value}, _from, state) do
  :ets.insert(:my_cache, {key, value})
  {:reply, :ok, state}
end

The table dies with its owner. If the cache must survive restarts of the writer, make the owner a separate, minimal process.


Anti-patterns

  • Bottleneck GenServer: every read goes through one process. Use ETS, the database, or PartitionSupervisor.
  • God process: one GenServer owning unrelated state. Split by responsibility.
  • Process as a code-organisation tool: if there's no state, concurrency or failure isolation to manage, write a plain module.
  • Unawaited Task.async: the reply message leaks into the caller's mailbox. Await it, or use Task.Supervisor.start_child/2.

Testing

Start processes with start_supervised!/1 (stopped after each test) and observe exits with a monitor, never with Process.sleep:

test "a room stops when the last member leaves" do
  pid = start_supervised!({MyApp.Room, room_id: "lobby"})
  ref = Process.monitor(pid)

  :ok = MyApp.Room.join(pid, "alice")
  :ok = MyApp.Room.leave(pid, "alice")

  assert_receive {:DOWN, ^ref, :process, ^pid, :normal}
end

Name test processes uniquely (or not at all) so async: true tests don't collide: start_supervised!({MyApp.Cache, name: :"cache_#{System.unique_integer()}"}) is fine in tests because the atom count is bounded by the test count. See the testing-essentials skill.

Phoenix Auth Customization

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Use the generated auth; extend it, don't rewrite it — keep UserAuth, UserToken, the session controller and the generated tests. Add fields and functions next to them; never paste a pre-1.8 User module or UserAuth over the generated one.
  2. Never edit the generated auth migration — add a new migration for each new column.
  3. Add a registration_changeset/3 that pipes email_changeset/3 — 1.8 has no registration changeset: register_user/1 uses email_changeset/3, which the settings page also uses to change email. Requiring a new field inside email_changeset breaks email changes.
  4. Registration is email-only (magic link) — don't add a password input to registration. A password set at sign-up is silently dropped by email_changeset, and if you make it stick, login_user_by_magic_link/1 raises for unconfirmed users with a password (see "Mixing magic link and password registration" in mix help phx.gen.auth).
  5. Add only the new line to the schema — keep field :authenticated_at, :utc_datetime, virtual: true (sudo mode reads it) and timestamps(type: :utc_datetime).
  6. Use the generated fixtures; add the new field to valid_user_attributes/1 — user_fixture/1 already confirms the user via a magic link; unconfirmed_user_fixture/1, user_scope_fixture/0,1 and set_password/1 already exist.
  7. Never cast privileged fields — :role, :confirmed_at, :org_id, :hashed_password are set with change/2 / put_change/3 in a dedicated context function, never from form params.
  8. Uniqueness = unique index + unique_constraint — plus unsafe_validate_unique for early feedback, skipped during phx-change via the generator's validate_unique: false option.
  9. Update every caller of the changed changeset — the registration LiveView's mount and "validate" handler, register_user/1, and the generated accounts_test.exs tests that call register_user(%{email: ...}) directly.

What phx.gen.auth Generates (1.8)

mix phx.gen.auth Accounts User users --live      # or --no-live for controllers
  • lib/my_app/accounts.ex, accounts/user.ex, accounts/user_token.ex, accounts/user_notifier.ex, accounts/scope.ex
  • lib/my_app_web/user_auth.ex, controllers/user_session_controller.ex
  • --live: live/user_live/registration.ex, login.ex, confirmation.ex, settings.ex; --no-live: registration, session and settings controllers + templates
  • test/support/fixtures/accounts_fixtures.ex and tests for all of the above
  • a config :my_app, :scopes entry so later phx.gen.live/phx.gen.context runs generate scoped code (see the phoenix-scopes-and-generators skill)

Users register with an email only, receive a magic link, and may set a password later in settings.


Adding a Field (username)

1. Migration

mix ecto.gen.migration add_username_to_users
defmodule MyApp.Repo.Migrations.AddUsernameToUsers do
  use Ecto.Migration

  def change do
    alter table(:users) do
      # citext (enabled by the auth migration) makes uniqueness case-insensitive, like email
      add :username, :citext, null: false
    end

    create unique_index(:users, [:username])
  end
end

On a table that already has rows, add the column nullable, backfill, then add NOT NULL and build the unique index with concurrently: true in later migrations (the steps are in the ecto-migrations-safety skill).

2. Schema — add one line

schema "users" do
  # ...generated fields stay as they are
  field :username, :string
end

3. A registration changeset that builds on email_changeset

@doc """
A user changeset for registration. Same options as `email_changeset/3`.
"""
def registration_changeset(user, attrs, opts \\ []) do
  user
  |> email_changeset(attrs, opts)
  |> cast(attrs, [:username])
  |> validate_username(opts)
end

defp validate_username(changeset, opts) do
  changeset =
    changeset
    |> validate_required([:username])
    |> validate_length(:username, min: 3, max: 30)
    |> validate_format(:username, ~r/^[a-zA-Z0-9_]+$/,
      message: "only letters, numbers, and underscores"
    )

  if Keyword.get(opts, :validate_unique, true) do
    changeset
    |> unsafe_validate_unique(:username, MyApp.Repo)
    |> unique_constraint(:username)
  else
    changeset
  end
end

4. Point the context at it

# accounts.ex
def register_user(attrs) do
  %User{}
  |> User.registration_changeset(attrs)
  |> Repo.insert()
end

def change_user_registration(%User{} = user, attrs \\ %{}, opts \\ []) do
  User.registration_changeset(user, attrs, opts)
end

5. Registration LiveView

Swap change_user_email for change_user_registration in mount/3 and the "validate" handler, and add the input. The "save" handler already passes all user_params to register_user/1.

def mount(_params, _session, socket) do
  changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false)
  {:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]}
end

def handle_event("validate", %{"user" => user_params}, socket) do
  changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false)
  {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))}
end

Keep the generated first mount/3 clause that redirects already-logged-in users, and keep @impl true on the first clause.

<.form for={@form} id="registration_form" phx-submit="save" phx-change="validate">
  <.input field={@form[:email]} type="email" label="Email" autocomplete="username" required />
  <.input field={@form[:username]} type="text" label="Username" required />

  <.button phx-disable-with="Creating account..." class="btn btn-primary w-full">
    Create an account
  </.button>
</.form>

With --no-live, make the same change in UserRegistrationController.new/2 and registration_new.html.heex.


Fixtures and Generated Tests

Only valid_user_attributes/1 changes:

def unique_user_username, do: "user#{System.unique_integer([:positive])}"

def valid_user_attributes(attrs \\ %{}) do
  Enum.into(attrs, %{
    email: unique_user_email(),
    username: unique_user_username()
  })
end

Everything else is already there: user_fixture/1 (confirmed via magic link), unconfirmed_user_fixture/1, user_scope_fixture/0,1, set_password/1 (for password-login tests), register_and_log_in_user/1 in ConnCase. Do not add password: or confirmed_at: to the attributes.

Then fix the generated tests that bypass fixtures — e.g. in accounts_test.exs, register_user(%{email: email}) becomes register_user(valid_user_attributes(email: email)). Registration tests that submit valid_user_attributes/1 keep working; ones that submit a literal %{"email" => ...} and expect success need a "username".

describe "register_user/1" do
  test "requires username" do
    {:error, changeset} = Accounts.register_user(%{email: unique_user_email()})
    assert "can't be blank" in errors_on(changeset).username
  end

  test "enforces unique username case-insensitively" do
    %{username: username} = user_fixture()

    {:error, changeset} =
      Accounts.register_user(valid_user_attributes(username: String.upcase(username)))

    assert "has already been taken" in errors_on(changeset).username
  end

  test "changing email does not require username" do
    user = user_fixture()
    changeset = Accounts.change_user_email(user, %{email: unique_user_email()})
    assert changeset.valid?
  end
end

Profile Fields and Privileged Fields

User-editable fields that aren't part of sign-up get their own changeset and a scope-taking context function, like the generated settings functions:

# user.ex
def profile_changeset(user, attrs) do
  user
  |> cast(attrs, [:display_name, :bio])
  |> validate_length(:display_name, max: 50)
  |> validate_length(:bio, max: 500)
end

# accounts.ex
def update_user_profile(%Scope{user: user}, attrs) do
  user
  |> User.profile_changeset(attrs)
  |> Repo.update()
end

Privileged fields (a role, an org membership) are never in a cast list. Add the column with a safe default (field :role, Ecto.Enum, values: [:member, :admin], default: :member), set it from an admin-only function with Ecto.Changeset.change(user, role: :admin), and expose it to authorization through the scope — see the phoenix-authorization-patterns skill.


See the phoenix-liveview-auth skill for on_mount hooks, sudo mode and routes. See the ecto-changeset-patterns skill for changeset composition. See the testing-essentials skill for general testing patterns.

Phoenix Authorization Patterns

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Pass current_scope as the first argument to every context call — Blog.get_post!(socket.assigns.current_scope, id), never Blog.get_post!(id) or Repo.get!(Post, id) with an id from params. Loading by a client id without the scope is an IDOR.
  2. Scope the query, not just the check — get_post!(%Scope{} = scope, id) is Repo.get_by!(Post, id: id, user_id: scope.user.id): another user's record raises Ecto.NoResultsError (a 404), so existence isn't leaked and no separate check can be forgotten.
  3. Authorize inside the context function — mutations re-check ownership or call the policy (true = post.user_id == scope.user.id, as the 1.8 generator does), so every caller (LiveView, controller, job) is covered.
  4. Authorize in handle_params/3 as well as mount/3 — push_patch re-runs handle_params but not mount; load any record whose id arrives in the URL through the scope where the params arrive.
  5. Authorize every handle_event/3 on the server — hiding a button is UX, not security; events can be crafted with any params.
  6. Never cast ownership or privileged fields — :user_id, :org_id, :role, :confirmed_at, :deleted_at. Set them with put_change/3 or Ecto.build_assoc/3 from the scope, as the generator's changeset(post, attrs, scope) does.
  7. Policies take %Scope{}, not %User{} — the scope is what the web layer has, and it can carry org and role.
  8. Put roles and orgs on the Scope struct — extend the generated Scope (its moduledoc says to) and fill it once in an on_mount hook / plug, instead of threading extra arguments.
  9. Scope PubSub topics too — subscribe and broadcast on "user:#{scope.user.id}:posts" (the generator's subscribe_posts(scope)), never a global topic.
  10. Test the unauthorized path — another user's id must raise Ecto.NoResultsError (or return {:error, :unauthorized}); every mutating event needs a test proving that.

Scoped Contexts (the 1.8 generator pattern)

mix phx.gen.live Blog Post posts title:string body:text in an app with phx.gen.auth generates scoped contexts (the generated module, with its broadcasts, is in the phoenix-pubsub-patterns skill). Follow the shape for hand-written contexts. The two authorization points:

# Reads: the owner filter is part of the query
def get_post!(%Scope{} = scope, id) do
  Repo.get_by!(Post, id: id, user_id: scope.user.id)
end

# Writes: re-check ownership of the struct the caller passes in
def update_post(%Scope{} = scope, %Post{} = post, attrs) do
  true = post.user_id == scope.user.id

  post
  |> Post.changeset(attrs, scope)
  |> Repo.update()
end

The true = ... match crashes on a mismatch — correct when the caller should already have loaded the post through get_post!/2; a crash there means a bug, not a user error.

A repo-level prepare_query/3 guard for multi-tenant org_id filtering is in the ecto-queries-performance skill.

Mass assignment: ownership comes from the scope

The generator's changeset never casts the owner; it sets it from the scope:

post
|> cast(attrs, [:title, :body])
|> put_change(:user_id, user_scope.user.id)

For the bad/good pair and foreign keys the user chooses (folder_id), see the ecto-changeset-patterns skill.


LiveViews

defmodule MyAppWeb.PostLive.Index do
  use MyAppWeb, :live_view

  alias MyApp.Blog

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope}>
      <div id="posts" phx-update="stream">
        <div :for={{id, post} <- @streams.posts} id={id}>
          {post.title}
          <.link
            phx-click={JS.push("delete", value: %{id: post.id}) |> hide("##{id}")}
            data-confirm="Are you sure?"
          >
            Delete
          </.link>
        </div>
      </div>
    </Layouts.app>
    """
  end

  @impl true
  def mount(_params, _session, socket) do
    {:ok, stream(socket, :posts, Blog.list_posts(socket.assigns.current_scope))}
  end

  @impl true
  def handle_event("delete", %{"id" => id}, socket) do
    scope = socket.assigns.current_scope
    post = Blog.get_post!(scope, id)
    {:ok, _} = Blog.delete_post(scope, post)

    {:noreply, stream_delete(socket, :posts, post)}
  end
end

The id comes from the client, but get_post!/2 only finds the caller's own posts. data-confirm is a UX guard against misclicks, nothing more.

handle_params: patches skip mount

# Bad — mount checks, but a push_patch to /posts/OTHER_ID/edit only runs handle_params
def handle_params(%{"id" => id}, _uri, socket) do
  {:noreply, assign(socket, :post, Repo.get!(Post, id))}
end
@impl true
def handle_params(%{"id" => id}, _uri, socket) do
  post = Blog.get_post!(socket.assigns.current_scope, id)
  {:noreply, assign(socket, post: post, form: to_form(Blog.change_post(socket.assigns.current_scope, post)))}
end

def handle_params(_params, _uri, socket) do
  {:noreply, assign(socket, post: nil, form: nil)}
end

Roles and Orgs on the Scope

Extend the generated struct with org and org_role (plus a put_org/3 builder) and keep for_user/1, which still returns nil for guests. Fill those fields once, after authentication, from a membership lookup through the current scope (Orgs.get_membership(scope, slug)), never from a param or a cast field. Do it in both an on_mount hook (websocket mount and live navigation) and a plug (HTTP render and controllers). Org-owned queries then filter on scope.org.id, and policies match on org_role (below).

The struct, the plug and hook, the router wiring, the config :my_app, :scopes entry for --scope org and the test helpers generated code expects are in the phoenix-scopes-and-generators skill.

A global role (site admin) belongs on the user as a non-cast field (see the phoenix-auth-customization skill) and is read as scope.user.role.


Policy Modules

When rules go beyond "owner only" (admins, org roles, published content), centralize them in a policy that takes the scope, and call it from the context.

defmodule MyApp.Blog.Policy do
  alias MyApp.Accounts.{Scope, User}
  alias MyApp.Blog.Post

  # assumes a non-cast `role` field on User
  def authorize(%Scope{user: %User{role: :admin}}, _action, %Post{}), do: :ok

  def authorize(%Scope{user: %User{id: id}}, action, %Post{user_id: id})
      when action in [:update, :delete],
      do: :ok

  def authorize(%Scope{org: %{id: org_id}, org_role: :editor}, :update, %Post{org_id: org_id}),
    do: :ok

  def authorize(_scope, :view, %Post{published: true}), do: :ok
  def authorize(_scope, _action, _resource), do: {:error, :unauthorized}
end
# In the context — replaces the owner-only `true = ...` check
def delete_post(%Scope{} = scope, %Post{} = post) do
  with :ok <- Policy.authorize(scope, :delete, post) do
    Repo.delete(post)
  end
end

The catch-all also covers guests (nil scope). For an admin who may load any post, give the context an explicit query for that case (get_post_for_admin!/2 that pattern-matches the admin scope) rather than unscoping get_post!/2.


Controllers

Same rules; the plug assigns the same current_scope.

def delete(conn, %{"id" => id}) do
  scope = conn.assigns.current_scope
  post = Blog.get_post!(scope, id)
  {:ok, _post} = Blog.delete_post(scope, post)

  conn
  |> put_flash(:info, "Post deleted.")
  |> redirect(to: ~p"/posts")
end

Ecto.NoResultsError renders as a 404 (via phoenix_ecto), so a guessed id looks like a missing page.


Testing Authorization

describe "authorization" do
  setup :register_and_log_in_user

  test "a user cannot load another user's post", %{conn: conn} do
    other_post = post_fixture(user_scope_fixture())

    assert_raise Ecto.NoResultsError, fn -> live(conn, ~p"/posts/#{other_post}") end
  end

  test "context refuses another scope", %{scope: scope} do
    other_scope = user_scope_fixture()
    post = post_fixture(scope)

    assert_raise Ecto.NoResultsError, fn -> Blog.get_post!(other_scope, post.id) end
    assert_raise MatchError, fn -> Blog.delete_post(other_scope, post) end
  end

  test "list is scoped", %{scope: scope} do
    post = post_fixture(scope)
    _other = post_fixture(user_scope_fixture())

    assert Blog.list_posts(scope) == [post]
  end
end

register_and_log_in_user/1 puts conn, user and scope in the test context; post_fixture/2 takes the scope first.


See the phoenix-liveview-auth skill for authentication (on_mount, live_session, sudo mode). See the phoenix-pubsub-patterns skill for scoped topics. See the ecto-changeset-patterns skill for changeset composition.

Phoenix Channels Essentials

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2 — October 2026

For non-LiveView real-time features: mobile clients, SPAs, external APIs, inter-service communication.

RULES — Follow these with no exceptions

  1. Authenticate in connect/3; return :error otherwise. Same-origin browser clients can reuse the phx.gen.auth session through connect_info: [session: @session_options]; other clients use a Phoenix.Token verified with an explicit max_age (keep it short, e.g. 86_400; it can't be revoked).
  2. Make sockets disconnectable on logout. id/1 returns a topic you can broadcast "disconnect" to. With session auth, return the session's live_socket_id and the generated log_out_user/1 already does it.
  3. Authorize in join/3 through the scope — load the topic's resource with socket.assigns.current_scope and return {:error, %{reason: "unauthorized"}} if that fails. The topic string is client input.
  4. Keep check_origin on in production. Turning it off for a cookie-authenticated socket leaves the CSRF check as the only guard against cross-site WebSocket hijacking; Phoenix raises if both check_origin and check_csrf are false.
  5. Keep channel modules thin — delegate to context functions that take the scope.
  6. Reply when the client needs the outcome ({:reply, {:ok, payload} | {:error, payload}, socket}). {:noreply, socket} is fine for fire-and-forget events (typing indicators, the generator's "shout").
  7. Use intercept/handle_out only to filter or customize a broadcast per subscriber. An intercepted event is encoded once per subscriber instead of once per topic.
  8. Use Phoenix.Presence for who's online, in channels and LiveViews. In channel tests, assert_push "presence_state", _ before you read Presence.list/1.

Endpoint Configuration

# lib/my_app_web/endpoint.ex
socket "/socket", MyAppWeb.UserSocket,
  websocket: [connect_info: [session: @session_options]],
  longpoll: false

@session_options is the attribute the generated endpoint already defines for /live. check_origin defaults to true (the request's origin must match the endpoint's url: [host: ...]); generated dev.exs turns it off. If you serve several hosts, list them in prod config:

# config/runtime.exs
config :my_app, MyAppWeb.Endpoint,
  check_origin: ["https://example.com", "https://www.example.com"]

Native mobile clients don't send origin, so the check doesn't apply to them; they must use token auth.


Socket Authentication

Browser clients: reuse the session (revocable)

defmodule MyAppWeb.UserSocket do
  use Phoenix.Socket

  alias MyApp.Accounts
  alias MyApp.Accounts.Scope

  channel "room:*", MyAppWeb.RoomChannel

  @impl true
  def connect(_params, socket, %{session: %{"user_token" => token} = session}) do
    case Accounts.get_user_by_session_token(token) do
      {user, _token_inserted_at} ->
        {:ok,
         socket
         |> assign(:current_scope, Scope.for_user(user))
         |> assign(:live_socket_id, session["live_socket_id"])}

      nil ->
        :error
    end
  end

  # No session cookie, failed CSRF check (session is nil), or a guest.
  def connect(_params, _socket, _connect_info), do: :error

  # Same id as the LiveView socket: UserAuth.log_out_user/1 broadcasts
  # "disconnect" to it, and the deleted session token blocks the reconnect.
  @impl true
  def id(socket), do: socket.assigns.live_socket_id
end
// assets/js/user_socket.js: the session is only read if _csrf_token is sent
import {Socket} from "phoenix"

const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
const socket = new Socket("/socket", {params: {_csrf_token: csrfToken}})
socket.connect()
export default socket

Other clients: Phoenix.Token

Only sign a token for a logged-in user. A plug in the :browser pipeline (after :fetch_current_scope_for_user) keeps guests working:

# lib/my_app_web/user_auth.ex
def put_socket_token(conn, _opts) do
  case conn.assigns[:current_scope] do
    %{user: %{id: user_id}} ->
      assign(conn, :socket_token, Phoenix.Token.sign(conn, "user socket", user_id))

    _guest ->
      assign(conn, :socket_token, nil)
  end
end
<%!-- root.html.heex, in <head> --%>
<meta :if={@socket_token} name="socket-token" content={@socket_token} />
const token = document.querySelector("meta[name='socket-token']")?.content
if (token) {
  const socket = new Socket("/socket", {authToken: token})
  socket.connect()
}
# endpoint.ex: auth_token: true sends the token in a header, not the URL
socket "/socket", MyAppWeb.UserSocket, websocket: true, longpoll: false, auth_token: true

# user_socket.ex
@impl true
def connect(_params, socket, %{auth_token: token}) when is_binary(token) do
  # Always pass max_age (1 day here). Don't extend it: the token can't be revoked.
  with {:ok, user_id} <- Phoenix.Token.verify(socket, "user socket", token, max_age: 86_400),
       %User{} = user <- Accounts.get_user(user_id) do
    {:ok, assign(socket, :current_scope, Scope.for_user(user))}
  else
    _ -> :error
  end
end

def connect(_params, _socket, _connect_info), do: :error

@impl true
def id(socket), do: "user_socket:#{socket.assigns.current_scope.user.id}"

Accounts.get_user/1 is Repo.get(User, id), which you add; the generator only has get_user!/1. A mobile client sends the token from your API login response instead of a meta tag.

On logout, close that user's open sockets. Add this to the generated log_out_user/1 before the session is renewed:

# assigns[...]: the generated UserAuth tests call log_out_user/1 without it
if scope = conn.assigns[:current_scope] do
  MyAppWeb.Endpoint.broadcast("user_socket:#{scope.user.id}", "disconnect", %{})
end

This closes the user's sockets on every device; clients still holding a valid token reconnect. A token copied before logout stays valid until max_age, so use session auth when you need real revocation.

# No authentication: anyone can connect and join
def connect(_params, socket, _connect_info), do: {:ok, socket}

Topic Authorization

defmodule MyAppWeb.RoomChannel do
  use MyAppWeb, :channel

  alias MyApp.Chat

  @impl true
  def join("room:" <> room_id, _payload, socket) do
    # fetch_room/2 scopes the lookup and returns {:error, :not_found} for
    # rooms the user can't see, including a non-numeric id.
    case Chat.fetch_room(socket.assigns.current_scope, room_id) do
      {:ok, room} -> {:ok, assign(socket, :room, room)}
      {:error, :not_found} -> {:error, %{reason: "unauthorized"}}
    end
  end
end
# Any authenticated user can join any room
def join("room:" <> room_id, _payload, socket) do
  {:ok, assign(socket, :room_id, room_id)}
end

Message Patterns

handle_in: reply when the client needs the outcome

@impl true
def handle_in("new_msg", %{"body" => body}, socket) do
  %{current_scope: scope, room: room} = socket.assigns

  case Chat.create_message(scope, room, %{"body" => body}) do
    {:ok, message} ->
      broadcast!(socket, "new_msg", %{id: message.id, body: message.body, user_id: message.user_id})
      {:reply, :ok, socket}

    {:error, changeset} ->
      errors = Ecto.Changeset.traverse_errors(changeset, &MyAppWeb.CoreComponents.translate_error/1)
      {:reply, {:error, %{errors: errors}}, socket}
  end
end

# Fire-and-forget: nobody waits for a result
def handle_in("typing", _payload, socket) do
  broadcast_from!(socket, "typing", %{user_id: socket.assigns.current_scope.user.id})
  {:noreply, socket}
end

Push explicit maps. A broadcast payload goes to every subscriber as-is, so never broadcast whole Ecto structs (hidden fields, unloaded associations).

CallGoes to
push(socket, event, payload)this client only
broadcast!(socket, event, payload)everyone on the topic, including the sender
broadcast_from!(socket, event, payload)everyone except the sender
MyAppWeb.Endpoint.broadcast(topic, event, payload)a topic, from outside a channel (contexts, jobs)

intercept / handle_out: per-subscriber filtering

intercept ["new_msg"]

@impl true
def handle_out("new_msg", payload, socket) do
  if Chat.blocked?(socket.assigns.current_scope, payload.user_id) do
    {:noreply, socket}
  else
    push(socket, "new_msg", payload)
    {:noreply, socket}
  end
end

Declare intercept above the handle_out/3 clauses. Phoenix prints a compile-time warning for a handle_out/3 event that isn't intercepted yet, and an event that isn't intercepted never reaches handle_out/3.

handle_info: messages from PubSub and other processes

@impl true
def handle_info({:new_notification, notification}, socket) do
  push(socket, "notification", %{title: notification.title, body: notification.body})
  {:noreply, socket}
end

Presence

Generate it with mix phx.gen.presence, then add MyAppWeb.Presence to the supervision tree after {Phoenix.PubSub, ...} and before the endpoint.

In a channel

@impl true
def join("room:" <> room_id, _payload, socket) do
  case Chat.fetch_room(socket.assigns.current_scope, room_id) do
    {:ok, room} ->
      send(self(), :after_join)
      {:ok, assign(socket, :room, room)}

    {:error, :not_found} ->
      {:error, %{reason: "unauthorized"}}
  end
end

@impl true
def handle_info(:after_join, socket) do
  {:ok, _} =
    MyAppWeb.Presence.track(socket, to_string(socket.assigns.current_scope.user.id), %{
      online_at: System.system_time(:second),
      typing: false
    })

  push(socket, "presence_state", MyAppWeb.Presence.list(socket))
  {:noreply, socket}
end

Clients then receive "presence_diff" events automatically. Update metadata with MyAppWeb.Presence.update(socket, key, fn meta -> %{meta | typing: true} end).

In a LiveView

See the phoenix-pubsub-patterns skill: the LiveView tracks itself and handles presence_diff broadcasts in handle_info/2.


Channels vs LiveView vs PubSub

ChannelsLiveViewPubSub
ClientAny (mobile, SPA, IoT)BrowserServer processes only
RenderingClientServerNone
Use whenNon-browser clients, custom protocolsBrowser UI with real-time updatesProcess-to-process events

Testing Channels

defmodule MyAppWeb.RoomChannelTest do
  use MyAppWeb.ChannelCase

  import MyApp.AccountsFixtures
  import MyApp.ChatFixtures

  setup do
    scope = user_scope_fixture()
    room = room_fixture(scope)
    token = Phoenix.Token.sign(MyAppWeb.Endpoint, "user socket", scope.user.id)

    {:ok, socket} = connect(MyAppWeb.UserSocket, %{}, connect_info: %{auth_token: token})
    {:ok, _reply, socket} = subscribe_and_join(socket, "room:#{room.id}", %{})

    %{socket: socket, scope: scope, room: room}
  end

  test "new_msg replies ok and broadcasts", %{socket: socket} do
    ref = push(socket, "new_msg", %{"body" => "hello"})

    assert_reply ref, :ok
    assert_broadcast "new_msg", %{body: "hello"}
  end

  test "new_msg with invalid data replies with errors", %{socket: socket} do
    ref = push(socket, "new_msg", %{"body" => ""})

    assert_reply ref, :error, %{errors: %{body: _}}
  end

  test "a non-member cannot join", %{room: room} do
    other = user_scope_fixture()
    token = Phoenix.Token.sign(MyAppWeb.Endpoint, "user socket", other.user.id)
    {:ok, socket} = connect(MyAppWeb.UserSocket, %{}, connect_info: %{auth_token: token})

    assert {:error, %{reason: "unauthorized"}} = subscribe_and_join(socket, "room:#{room.id}", %{})
  end

  test "connect without a token is refused" do
    assert :error = connect(MyAppWeb.UserSocket, %{})
  end

  test "presence is tracked after join", %{socket: socket, scope: scope} do
    # :after_join runs after join returns; wait for its push before reading.
    assert_push "presence_state", _
    user_id = to_string(scope.user.id)

    assert %{^user_id => %{metas: [%{online_at: _}]}} = MyAppWeb.Presence.list(socket)
  end
end

The tests use the token socket. For a session-auth socket, pass the session through connect_info: %{session: %{"user_token" => token, "live_socket_id" => "users_sessions:test"}}, with the token from MyApp.Accounts.generate_user_session_token(user).


See the phoenix-pubsub-patterns skill for server-side PubSub, the phoenix-liveview-essentials skill for LiveView real-time patterns, and the testing-essentials skill before writing any _test.exs file.

Phoenix JSON API

Verified against Elixir 1.20, Phoenix 1.8, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Use the :api pipeline — plug :accepts, ["json"], no session, CSRF or browser headers; API clients authenticate with tokens
  2. Pass conn.assigns.current_scope as the first argument to every context call — Blog.get_post!(scope, id) loads by id and owner; loading or deleting by a client-supplied id alone is an IDOR
  3. Follow phx.gen.json — action_fallback, render(conn, :show, post: post) with a PostJSON module, ChangesetJSON for validation errors; json/2 is fine for one-off bodies
  4. The FallbackController handles every error your contexts return, plus a catch-all 500 — an unmatched {:error, _} otherwise raises FunctionClauseError; never put inspect(reason) in the response body
  5. Never return unbounded collections — parse page/per_page with Integer.parse/1 and clamp (1..100); order by a unique tiebreaker (desc: p.id); use keyset pagination for large or fast-changing tables
  6. Bearer tokens are random, stored hashed, expire, and are revocable — follow the generated UserToken pattern; never store or compare plaintext tokens
  7. Rate-limit login and token endpoints, and keep failures indistinguishable — same error for unknown email and wrong password; the generated get_user_by_email_and_password/2 already calls Bcrypt.no_user_verify/0 for unknown users
  8. Preload every association the JSON view renders — in the context function, not the view; post.user on an unloaded association is %Ecto.Association.NotLoaded{} (and the generated Post has no belongs_to :user until you add one)
  9. Version via URL prefix (/api/v1) — no as: option needed; Phoenix 1.8 apps use verified routes, not router helpers

Router

# lib/my_app_web/router.ex
pipeline :api do
  plug :accepts, ["json"]
end

pipeline :api_auth do
  plug MyAppWeb.Plugs.ApiAuth
end

scope "/api/v1", MyAppWeb.API.V1 do
  pipe_through :api

  post "/tokens", TokenController, :create
end

scope "/api/v1", MyAppWeb.API.V1 do
  pipe_through [:api, :api_auth]

  resources "/posts", PostController, except: [:new, :edit]
end

When v2 is needed, add scope "/api/v2", MyAppWeb.API.V2 and put only the controllers that changed under controllers/api/v2/.


Controller (generator shape, scoped)

phx.gen.json with scopes generates exactly this shape. get_post!/2 raises Ecto.NoResultsError, which phoenix_ecto turns into a 404 rendered by ErrorJSON — for another user's post as well as a missing one. Generated scoped controllers and their tests assume a pipeline that assigns :current_scope; see the phoenix-scopes-and-generators skill.

defmodule MyAppWeb.API.V1.PostController do
  use MyAppWeb, :controller

  alias MyApp.Blog
  alias MyApp.Blog.Post

  action_fallback MyAppWeb.FallbackController

  def index(conn, params) do
    page = parse_pos_int(params["page"], 1)
    per_page = params["per_page"] |> parse_pos_int(20) |> min(100)

    {posts, total} = Blog.paginate_posts(conn.assigns.current_scope, page: page, per_page: per_page)

    render(conn, :index, posts: posts, meta: %{page: page, per_page: per_page, total: total})
  end

  def create(conn, %{"post" => post_params}) do
    with {:ok, %Post{} = post} <- Blog.create_post(conn.assigns.current_scope, post_params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", ~p"/api/v1/posts/#{post}")
      |> render(:show, post: post)
    end
  end

  def show(conn, %{"id" => id}) do
    post = Blog.get_post!(conn.assigns.current_scope, id)
    render(conn, :show, post: post)
  end

  def update(conn, %{"id" => id, "post" => post_params}) do
    scope = conn.assigns.current_scope
    post = Blog.get_post!(scope, id)

    with {:ok, %Post{} = post} <- Blog.update_post(scope, post, post_params) do
      render(conn, :show, post: post)
    end
  end

  def delete(conn, %{"id" => id}) do
    scope = conn.assigns.current_scope
    post = Blog.get_post!(scope, id)

    with {:ok, %Post{}} <- Blog.delete_post(scope, post) do
      send_resp(conn, :no_content, "")
    end
  end

  # "abc", "0", "-5" and per_page[]=1 all fall back to the default instead of a 500
  defp parse_pos_int(value, default) when is_binary(value) do
    case Integer.parse(value) do
      {n, ""} when n > 0 -> n
      _ -> default
    end
  end

  defp parse_pos_int(_value, default), do: default
end
# IDOR: any authenticated user can read or delete any post by guessing ids
def delete(conn, %{"id" => id}) do
  post = Repo.get!(Post, id)
  {:ok, _} = Repo.delete(post)
  send_resp(conn, :no_content, "")
end

# 500 on "abc"; 0 or a negative value reaches LIMIT and Postgres errors
per_page = String.to_integer(params["per_page"])

JSON Views

# lib/my_app_web/controllers/api/v1/post_json.ex
defmodule MyAppWeb.API.V1.PostJSON do
  alias MyApp.Blog.Post

  def index(%{posts: posts, meta: meta}) do
    %{data: for(post <- posts, do: data(post)), meta: meta}
  end

  def show(%{post: post}) do
    %{data: data(post)}
  end

  defp data(%Post{} = post) do
    %{
      id: post.id,
      title: post.title,
      body: post.body,
      user_id: post.user_id,
      inserted_at: post.inserted_at
    }
  end
end

To render an association (say the author of a post in a shared feed), the schema needs it: the generated Post has field :user_id, :id, so replace that with belongs_to :user, MyApp.Accounts.User (the changeset's put_change(:user_id, scope.user.id) keeps working). Then preload :user in every context function whose result reaches the view (get_post!/2, create and update too, e.g. Repo.preload(post, :user)), and match a loaded struct in the view so a missed preload fails loudly instead of rendering %Ecto.Association.NotLoaded{}:

defp author(%MyApp.Accounts.User{} = user), do: %{id: user.id, email: user.email}

Choosing preload strategies and spotting N+1 queries: see the ecto-queries-performance skill.

List exactly the fields you expose. Never encode a schema struct directly (@derive Jason.Encoder without only:): the next field someone adds (hashed_password, role) ships to clients.


FallbackController

defmodule MyAppWeb.FallbackController do
  use MyAppWeb, :controller

  alias Plug.Conn.Status

  require Logger

  def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
    conn
    |> put_status(:unprocessable_entity)
    |> put_view(json: MyAppWeb.ChangesetJSON)
    |> render(:error, changeset: changeset)
  end

  def call(conn, {:error, :not_found}), do: error(conn, :not_found)
  def call(conn, {:error, :unauthorized}), do: error(conn, :unauthorized)
  def call(conn, {:error, :forbidden}), do: error(conn, :forbidden)

  def call(conn, {:error, {:rate_limited, retry_after_ms}}) do
    conn
    |> put_resp_header("retry-after", to_string(div(retry_after_ms, 1000) + 1))
    |> error(:too_many_requests)
  end

  # Catch-all: log the reason, return a generic 500 body
  def call(conn, {:error, reason}) do
    Logger.error("Unhandled API error: #{inspect(reason)}")
    error(conn, :internal_server_error)
  end

  # Same body shape as the generated ErrorJSON: %{errors: %{detail: "Not Found"}}
  defp error(conn, status) do
    code = Status.code(status)

    conn
    |> put_status(code)
    |> json(%{errors: %{detail: Status.reason_phrase(code)}})
  end
end

ChangesetJSON is generated the first time you run phx.gen.json. If you hand-write the API, add it:

defmodule MyAppWeb.ChangesetJSON do
  def error(%{changeset: changeset}) do
    %{errors: Ecto.Changeset.traverse_errors(changeset, &MyAppWeb.CoreComponents.translate_error/1)}
  end
end

If clients need machine-readable errors, render RFC 9457 problem details instead (type, title, status, detail, content type application/problem+json) — pick one error shape and use it for every error, including the 404/500 that ErrorJSON renders for exceptions.


Bearer Token Authentication

Store a SHA-256 hash of a random token, like the generated magic-link tokens. A database dump then contains no usable tokens, and a lookup by hash needs no constant-time comparison.

# lib/my_app/accounts/user_token.ex — add next to the generated builders
@api_token_validity_in_days 30

def build_api_token(user) do
  token = :crypto.strong_rand_bytes(@rand_size)

  {Base.url_encode64(token, padding: false),
   %UserToken{token: :crypto.hash(@hash_algorithm, token), context: "api", user_id: user.id}}
end

def verify_api_token_query(token) do
  case Base.url_decode64(token, padding: false) do
    {:ok, decoded} ->
      query =
        from t in by_token_and_context_query(:crypto.hash(@hash_algorithm, decoded), "api"),
          join: user in assoc(t, :user),
          where: t.inserted_at > ago(@api_token_validity_in_days, "day"),
          select: user

      {:ok, query}

    :error ->
      :error
  end
end
# lib/my_app/accounts.ex
def create_user_api_token(%User{} = user) do
  {encoded, user_token} = UserToken.build_api_token(user)
  Repo.insert!(user_token)
  encoded
end

def fetch_user_by_api_token(token) do
  with {:ok, query} <- UserToken.verify_api_token_query(token),
       %User{} = user <- Repo.one(query) do
    {:ok, user}
  else
    _ -> :error
  end
end

Revoke with Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: "api"])). The generated password change already deletes every token of the user, API tokens included.

defmodule MyAppWeb.Plugs.ApiAuth do
  import Plug.Conn

  alias MyApp.Accounts
  alias MyApp.Accounts.Scope

  def init(opts), do: opts

  def call(conn, _opts) do
    with ["Bearer " <> token] <- get_req_header(conn, "authorization"),
         {:ok, user} <- Accounts.fetch_user_by_api_token(token) do
      assign(conn, :current_scope, Scope.for_user(user))
    else
      _ ->
        conn
        |> put_status(:unauthorized)
        |> Phoenix.Controller.json(%{errors: %{detail: "Unauthorized"}})
        |> halt()
    end
  end
end

Issuing tokens (rate-limited)

defmodule MyAppWeb.API.V1.TokenController do
  use MyAppWeb, :controller

  alias MyApp.Accounts
  alias MyApp.Accounts.User

  action_fallback MyAppWeb.FallbackController

  def create(conn, %{"email" => email, "password" => password}) do
    key = "api-login:#{:inet.ntoa(conn.remote_ip)}"

    with {:allow, _count} <- MyApp.RateLimit.hit(key, :timer.minutes(1), 10),
         %User{} = user <- Accounts.get_user_by_email_and_password(email, password) do
      conn
      |> put_status(:created)
      |> json(%{data: %{token: Accounts.create_user_api_token(user)}})
    else
      {:deny, retry_after_ms} -> {:error, {:rate_limited, retry_after_ms}}
      # One response for unknown email and wrong password
      nil -> {:error, :unauthorized}
    end
  end
end

MyApp.RateLimit is a Hammer 7 module: defmodule MyApp.RateLimit, do: use(Hammer, backend: :ets), started in your supervision tree as {MyApp.RateLimit, clean_period: :timer.minutes(1)}. The ETS backend counts per node; use a shared backend (Redis) when you run several nodes. Behind a proxy, conn.remote_ip is the proxy's address unless you rewrite it from x-forwarded-for (only when you trust the proxy).


Pagination

Ordering by inserted_at alone is not stable — rows with equal timestamps swap between pages, so OFFSET pagination skips or duplicates them. Always add a unique tiebreaker.

# lib/my_app/blog.ex
def paginate_posts(%Scope{} = scope, opts) do
  page = Keyword.fetch!(opts, :page)
  per_page = Keyword.fetch!(opts, :per_page)
  base = from(p in Post, where: p.user_id == ^scope.user.id)

  posts =
    from(p in base,
      order_by: [desc: p.inserted_at, desc: p.id],
      limit: ^per_page,
      offset: ^((page - 1) * per_page)
    )
    |> Repo.all()

  {posts, Repo.aggregate(base, :count)}
end

Keyset (cursor) pagination — use it for large tables, infinite scroll, or data that changes while clients page. Cost doesn't grow with page depth and inserts don't shift pages. Return the last row's {inserted_at, id} as an opaque cursor, and decode and validate it like any other param.

def list_posts_after(%Scope{} = scope, cursor, limit) do
  query =
    from(p in Post,
      where: p.user_id == ^scope.user.id,
      order_by: [desc: p.inserted_at, desc: p.id],
      limit: ^limit
    )

  query =
    case cursor do
      nil ->
        query

      {inserted_at, id} ->
        from(p in query,
          where: p.inserted_at < ^inserted_at or (p.inserted_at == ^inserted_at and p.id < ^id)
        )
    end

  Repo.all(query)
end

Back it with an index on (user_id, inserted_at, id).


Production Concerns

  • CORS — only needed when browsers on another origin call the API. Use Corsica in the endpoint, before the router, so preflight OPTIONS requests get an answer before routing:
    plug Corsica,
      origins: ["https://app.example.com"],
      allow_headers: ["authorization", "content-type"],
      allow_methods: ["GET", "POST", "PUT", "PATCH", "DELETE"]
    
    Never origins: "*" on an API that reads cookies.
  • Body size — Plug.Parsers defaults to length: 8_000_000 (8 MB) for every parser. Lower it in the endpoint for JSON-only APIs, and raise it only for multipart: parsers: [:urlencoded, {:multipart, length: 20_000_000}, :json].
  • Idempotency keys — for non-idempotent POSTs that clients retry (payments, orders), accept an Idempotency-Key header, store it with a unique index scoped to the user, and return the stored response on a repeat instead of creating a second record.
  • OpenAPI — OpenApiSpex generates the spec from controller operation macros (use OpenApiSpex.ControllerSpecs), and its OpenApiSpex.Plug.CastAndValidate plug validates requests against that spec.

Testing API Endpoints

defmodule MyAppWeb.API.V1.PostControllerTest do
  use MyAppWeb.ConnCase

  import MyApp.AccountsFixtures
  import MyApp.BlogFixtures

  setup %{conn: conn} do
    scope = user_scope_fixture()
    token = MyApp.Accounts.create_user_api_token(scope.user)

    conn =
      conn
      |> put_req_header("accept", "application/json")
      |> put_req_header("authorization", "Bearer #{token}")

    %{conn: conn, scope: scope}
  end

  test "paginates the caller's posts only", %{conn: conn, scope: scope} do
    for _ <- 1..25, do: post_fixture(scope)
    _other = post_fixture(user_scope_fixture())

    response = conn |> get(~p"/api/v1/posts?page=1&per_page=10") |> json_response(200)

    assert length(response["data"]) == 10
    assert response["meta"]["total"] == 25
  end

  test "garbage per_page falls back to the default", %{conn: conn} do
    assert %{"meta" => %{"per_page" => 20}} =
             conn |> get(~p"/api/v1/posts?per_page=abc") |> json_response(200)
  end

  test "another user's post is a 404", %{conn: conn} do
    other = post_fixture(user_scope_fixture())

    assert_error_sent 404, fn -> get(conn, ~p"/api/v1/posts/#{other}") end
  end

  test "returns 422 with errors on invalid data", %{conn: conn} do
    conn = post(conn, ~p"/api/v1/posts", post: %{title: ""})
    assert %{"title" => ["can't be blank"]} = json_response(conn, 422)["errors"]
  end

  test "returns 401 without a token" do
    conn = get(build_conn(), ~p"/api/v1/posts")
    assert json_response(conn, 401)["errors"]["detail"] == "Unauthorized"
  end
end

See the phoenix-authorization-patterns skill for permission checks beyond ownership. See the security-essentials skill for token, redirect and input-handling rules. See the testing-essentials skill for comprehensive testing patterns.

Phoenix LiveView Authentication

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Use the generated UserAuth; don't rewrite it — mix phx.gen.auth already ships the plugs, on_mount hooks, token reissue, remember-me and socket disconnects. Add routes to its live_session blocks; don't re-type mount_current_scope or paste pre-1.8 snippets over it.
  2. Use the generated names exactly — on_mount hooks are :mount_current_scope, :require_authenticated and :require_sudo_mode; the router's live_sessions are :current_user and :require_authenticated_user; the plug is :require_authenticated_user. There is no :require_authenticated_user hook and no :redirect_if_authenticated hook.
  3. Put login-only LiveViews inside the existing live_session :require_authenticated_user — its scope pipes through the :require_authenticated_user plug (HTTP render) and runs the :require_authenticated hook (websocket mount and live navigation). A live_session name may be defined only once in the router. Create a separate one only when its LiveViews need extra on_mount hooks (see below).
  4. For guests @current_scope is nil — Scope.for_user(nil) returns nil, not an empty scope. Guard with @current_scope && @current_scope.user (or :if={@current_scope}).
  5. Never make /users/log-in guest-only — logged-in users are sent there by sudo mode to re-authenticate, so a guest-only guard locks them out of settings. The generator mounts it under live_session :current_user; registration redirects logged-in users from its own mount/3.
  6. Gate sensitive pages with :require_sudo_mode — on_mount {MyAppWeb.UserAuth, :require_sudo_mode} in the LiveView (inside the authenticated live_session; it dereferences current_scope.user), and re-check Accounts.sudo_mode?/2 in the action that changes credentials.
  7. Disconnect live sockets when sessions die — log_out_user/1 broadcasts "disconnect" to the session's live_socket_id; after any Accounts call that returns expired tokens, call UserAuth.disconnect_sessions(tokens). Never drop :live_socket_id from the session.
  8. get_user_by_session_token/1 returns {user, token_inserted_at} or nil — destructure the tuple; never wrap it in a scope directly.
  9. In on_mount hooks, fully qualify Phoenix.LiveView.redirect/2 and Phoenix.LiveView.put_flash/3 — UserAuth imports Phoenix.Controller for its plugs; excluding those imports breaks the plug half.
  10. Test with the generated helpers — setup :register_and_log_in_user, log_in_user(conn, user, token_authenticated_at: ...), and assert {:error, {:redirect, %{to: path, flash: flash}}} from live/2.

What the Generator Gives You

mix phx.gen.auth Accounts User users --live (Phoenix 1.8):

PieceNameUsed for
Plug (in :browser):fetch_current_scope_for_userassigns :current_scope on every request (nil for guests)
Plug:require_authenticated_userredirects to ~p"/users/log-in", stores :user_return_to
on_mount:mount_current_scopeassigns :current_scope on the socket
on_mount:require_authenticatedhalts with redirect to log-in when no user
on_mount:require_sudo_modehalts unless the user authenticated in the last 10 minutes
live_session:current_userregister, log-in, magic-link confirmation (optional auth)
live_session:require_authenticated_usersettings (login required)
Functiondisconnect_sessions/1broadcasts "disconnect" for a list of %UserToken{}

With --no-live there are no on_mount hooks, live_sessions, live_socket_id or disconnect_sessions/1; instead you get a require_sudo_mode/2 plug and a redirect_if_user_is_authenticated/2 plug, used only for /users/register.


Adding Your Routes

Add to the generated blocks. Don't create a parallel live_session that replaces the generated hooks.

scope "/", MyAppWeb do
  pipe_through [:browser, :require_authenticated_user]

  live_session :require_authenticated_user,
    on_mount: [{MyAppWeb.UserAuth, :require_authenticated}] do
    live "/users/settings", UserLive.Settings, :edit
    live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email

    # your login-only LiveViews
    live "/posts", PostLive.Index, :index
    live "/posts/new", PostLive.Form, :new
  end

  post "/users/update-password", UserSessionController, :update_password
end

scope "/", MyAppWeb do
  pipe_through [:browser]

  live_session :current_user,
    on_mount: [{MyAppWeb.UserAuth, :mount_current_scope}] do
    live "/users/register", UserLive.Registration, :new
    live "/users/log-in", UserLive.Login, :new
    live "/users/log-in/:token", UserLive.Confirmation, :new

    # your pages that work with or without a user. (The generated
    # `get "/", PageController, :home` already owns "/": replace it to make "/" a LiveView.)
    live "/explore", ExploreLive, :index
  end

  post "/users/log-in", UserSessionController, :create
  delete "/users/log-out", UserSessionController, :delete
end

Need an extra check (admin, org membership) for a group of LiveViews? Give them their own live_session whose hook list starts with {MyAppWeb.UserAuth, :require_authenticated} (so the scope is assigned and checked first), and put it in a scope that pipes through [:browser, :require_authenticated_user]: live_session :admin, on_mount: [{MyAppWeb.UserAuth, :require_authenticated}, {MyAppWeb.AdminHooks, :require_admin}]. For a single LiveView, a module-level on_mount inside the existing session works too. See the phoenix-authorization-patterns skill.


The Generated Hooks (for reading, not retyping)

This is what user_auth.ex contains. If yours differs, you are looking at pre-1.8 code. All on_mount/4 clauses are grouped together.

def on_mount(:mount_current_scope, _params, session, socket) do
  {:cont, mount_current_scope(socket, session)}
end

def on_mount(:require_authenticated, _params, session, socket) do
  socket = mount_current_scope(socket, session)

  if socket.assigns.current_scope && socket.assigns.current_scope.user do
    {:cont, socket}
  else
    socket =
      socket
      |> Phoenix.LiveView.put_flash(:error, "You must log in to access this page.")
      |> Phoenix.LiveView.redirect(to: ~p"/users/log-in")

    {:halt, socket}
  end
end

def on_mount(:require_sudo_mode, _params, session, socket) do
  socket = mount_current_scope(socket, session)

  if Accounts.sudo_mode?(socket.assigns.current_scope.user, -10) do
    {:cont, socket}
  else
    socket =
      socket
      |> Phoenix.LiveView.put_flash(:error, "You must re-authenticate to access this page.")
      |> Phoenix.LiveView.redirect(to: ~p"/users/log-in")

    {:halt, socket}
  end
end

defp mount_current_scope(socket, session) do
  Phoenix.Component.assign_new(socket, :current_scope, fn ->
    {user, _} =
      if user_token = session["user_token"] do
        Accounts.get_user_by_session_token(user_token)
      end || {nil, nil}

    Scope.for_user(user)
  end)
end

assign_new/3 reuses the scope the plug already assigned during the HTTP render, so the token is looked up once per mount phase. sudo_mode? reads user.authenticated_at, a virtual field the session-token query fills from the token row.


Sudo Mode

Changing email or password requires a recent login. The generated settings LiveView adds the hook at module level, which runs after the live_session hooks:

defmodule MyAppWeb.UserLive.Settings do
  use MyAppWeb, :live_view

  on_mount {MyAppWeb.UserAuth, :require_sudo_mode}

  # ...
end

The redirect goes to /users/log-in, which shows a "reauthenticate" variant (email field read-only) when @current_scope is set. Use the same hook for your own sensitive pages (delete account, API keys, billing). Since the hook only runs on mount, re-check in the action itself — the generated update_password controller action does true = Accounts.sudo_mode?(user).


Magic Links, Logout and Socket Disconnects

  • Registration is email-only; Accounts.deliver_login_instructions(user, &url(~p"/users/log-in/#{&1}")) emails a magic link (valid 15 minutes). /users/log-in/:token (UserLive.Confirmation) submits to UserSessionController.create, which calls Accounts.login_user_by_magic_link/1.
  • The first magic-link login confirms the user and expires all their tokens; login_user_by_magic_link/1 returns {:ok, {user, expired_tokens}} and the controller calls UserAuth.disconnect_sessions(expired_tokens). update_user_password/2 does the same.
  • log_out_user/1 deletes the session token and broadcasts "disconnect" to live_socket_id ("users_sessions:" <> encoded token), so every open LiveView on that session (other tabs too) drops and re-runs its on_mount hooks without a valid token.

Follow the same pattern for anything new that invalidates tokens (account deletion, "log out everywhere"): return the expired %UserToken{} list from the context and pass it to disconnect_sessions/1 in the web layer.


@current_scope in Templates

<%!-- Guests: @current_scope is nil, so check it before .user --%>
<p :if={@current_scope}>Signed in as {@current_scope.user.email}</p>
<.link :if={!@current_scope} navigate={~p"/users/log-in"}>Log in</.link>

Every generated LiveView passes it to the layout: <Layouts.app flash={@flash} current_scope={@current_scope}>. Use bracket access assigns[:current_scope] only in a component that may render where no auth hook ran (the assign is then absent, not nil).

Context calls take the scope, never the user: Blog.list_posts(socket.assigns.current_scope).


Testing LiveView Auth

ConnCase (generated) provides register_and_log_in_user/1 and log_in_user/3.

describe "posts index" do
  setup :register_and_log_in_user

  test "renders for a logged-in user", %{conn: conn} do
    {:ok, lv, _html} = live(conn, ~p"/posts")
    assert has_element?(lv, "h1", "Listing Posts")
  end
end

test "redirects guests to log in", %{conn: conn} do
  assert {:error, {:redirect, %{to: path, flash: flash}}} = live(conn, ~p"/posts")
  assert path == ~p"/users/log-in"
  assert %{"error" => "You must log in to access this page."} = flash
end

test "sudo-mode page redirects when the login is stale", %{conn: conn} do
  stale = DateTime.add(DateTime.utc_now(:second), -11, :minute)

  {:ok, conn} =
    conn
    |> log_in_user(user_fixture(), token_authenticated_at: stale)
    |> live(~p"/users/settings")
    |> follow_redirect(conn, ~p"/users/log-in")

  assert conn.resp_body =~ "You must re-authenticate to access this page."
end

Calling a hook directly (as the generated user_auth_test.exs does):

test "require_authenticated halts without a token" do
  socket = %Phoenix.LiveView.Socket{
    endpoint: MyAppWeb.Endpoint,
    assigns: %{__changed__: %{}, flash: %{}}
  }

  assert {:halt, socket} = UserAuth.on_mount(:require_authenticated, %{}, %{}, socket)
  assert socket.assigns.current_scope == nil
end

See the phoenix-authorization-patterns skill for what a logged-in user may do. See the phoenix-auth-customization skill for adding fields to the generated user. See the testing-essentials skill for general LiveView testing patterns.

Phoenix LiveView Essentials

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2 — October 2026

RULES — Follow these with no exceptions

  1. @impl true before every callback — mount, handle_params, handle_event, handle_info, handle_async, render.
  2. Pass socket.assigns.current_scope as the first argument to every context call — Blog.get_post!(scope, id), never Blog.get_post!(id). Loading, updating or deleting by a client-supplied id without the scope is an IDOR. LiveViews call contexts, never Repo.
  3. Set every assign render/1 reads before the first render — static defaults in mount/3, URL-dependent ones (filter, sort, page) in handle_params/3.
  4. Subscribe and start timers in mount/3 inside if connected?(socket) — never in handle_params/3, which re-runs on every push_patch and stacks duplicate subscriptions.
  5. Load slow data with assign_async, stream_async or start_async — not with if connected?(socket) branches or blocking queries in mount/3.
  6. Collections are streams — stream/4, stream_insert/4, stream_delete/3, stream(..., reset: true) to refilter. The container needs an id and phx-update="stream".
  7. Forms: to_form/2 into @form; <.form for={@form} id="..." phx-change="validate" phx-submit="save">; <.button> directly inside the form (<.form> declares only inner_block — an actions slot is silently dropped, so the button never renders). Validate with to_form(changeset, action: :validate).
  8. Expected failures don't crash — on {:error, %Ecto.Changeset{}} re-assign the form; let only bugs raise.
  9. Function components declare attr/slot, with default: for optional attrs — never Map.get(assigns, :x, default) or assigns[:x].
  10. HEEx: {@x} in text and attributes, :for/:if attributes, <%!-- --%> comments; add :key to :for over plain lists.
  11. JS: reach for Phoenix.LiveView.JS commands first, then colocated hooks; every phx-hook element needs a unique DOM id.
  12. Reuse core_components.ex (<.input>, <.button>, <.table>, <.header>, <.list>, <.icon>) before writing new components.

Before finishing or reviewing a LiveView, walk through the LiveView checklist. For hook callbacks, push_event payloads, ColocatedJS/ColocatedCSS setup and runtime hooks, read the JS interop reference.

Related skills: phoenix-liveview-auth (live_session, on_mount auth), phoenix-pubsub-patterns (broadcasting), phoenix-uploads (allow_upload, consuming entries), testing-essentials (LiveView tests), phoenix-tailwind-daisyui (Tailwind v4 @source, daisyUI themes, extending core_components).


Lifecycle

HTTP GET       mount/3 -> handle_params/3 -> render/1   connected?(socket) == false, static HTML
WebSocket      mount/3 -> handle_params/3 -> render/1   connected?(socket) == true, now live
push_patch     handle_params/3 -> render/1              same process; mount/3 does NOT run
push_navigate  new LiveView mounts over the same socket (same live_session); no page reload
redirect/2     full HTTP page load

mount/3 runs twice per page load, so synchronous work in it runs twice. Async tasks only start once connected — that's why assign_async replaces the old if connected? loading pattern. push_navigate to a route in a different live_session falls back to a full page load.

A complete index LiveView

Based on mix phx.gen.live output (scoped context calls, subscription in mount, streams), plus a URL filter and single-item stream updates instead of the generator's re-fetch.

defmodule MyAppWeb.PostLive.Index do
  use MyAppWeb, :live_view

  alias MyApp.Blog
  alias MyApp.Blog.Post

  @impl true
  def mount(_params, _session, socket) do
    # Once per LiveView process. handle_params/3 re-runs on every push_patch.
    if connected?(socket) do
      Blog.subscribe_posts(socket.assigns.current_scope)
    end

    {:ok, assign(socket, :page_title, "Listing Posts")}
  end

  @impl true
  def handle_params(params, _uri, socket) do
    status = params["status"] || "all"
    # list_posts/2 is the generated list_posts/1 plus a filter option
    posts = Blog.list_posts(socket.assigns.current_scope, status: status)

    {:noreply,
     socket
     |> assign(:status, status)
     |> stream(:posts, posts, reset: true)}
  end

  @impl true
  def handle_event("delete", %{"id" => id}, socket) do
    scope = socket.assigns.current_scope
    # Scoped lookup: another user's id raises Ecto.NoResultsError instead of deleting
    post = Blog.get_post!(scope, id)
    {:ok, _} = Blog.delete_post(scope, post)

    {:noreply, stream_delete(socket, :posts, post)}
  end

  @impl true
  def handle_info({:created, %Post{} = post}, socket) do
    if visible?(post, socket.assigns.status) do
      {:noreply, stream_insert(socket, :posts, post, at: 0)}
    else
      {:noreply, socket}
    end
  end

  def handle_info({:updated, %Post{} = post}, socket) do
    # Existing DOM id -> updated in place; an edit can also move it out of the filter
    if visible?(post, socket.assigns.status) do
      {:noreply, stream_insert(socket, :posts, post)}
    else
      {:noreply, stream_delete(socket, :posts, post)}
    end
  end

  def handle_info({:deleted, %Post{} = post}, socket) do
    {:noreply, stream_delete(socket, :posts, post)}
  end

  # Broadcasts carry every post in the scope; keep the stream matching the URL filter.
  defp visible?(_post, "all"), do: true
  defp visible?(%Post{status: status}, filter), do: to_string(status) == filter
end
<Layouts.app flash={@flash} current_scope={@current_scope}>
  <.link patch={~p"/posts?status=draft"}>Drafts</.link>

  <div id="posts" phx-update="stream">
    <%!-- Non-stream child: needs its own id; shown only when it is the only child --%>
    <p id="posts-empty" class="hidden only:block">No posts yet.</p>
    <div :for={{dom_id, post} <- @streams.posts} id={dom_id}>
      <.link navigate={~p"/posts/#{post}"}>{post.title}</.link>
      <.link
        phx-click={JS.push("delete", value: %{id: post.id}) |> hide("##{dom_id}")}
        data-confirm="Are you sure?"
      >
        Delete
      </.link>
    </div>
  </div>
</Layouts.app>

The generated <.table rows={@streams.posts}> from core_components.ex handles the stream container for you.

Streams vs plain lists

  • Stream items aren't kept in server memory, so you can't Enum over @streams.posts. Keep counts or "is empty" state in a separate assign, or use the only: CSS trick above.
  • stream(socket, :posts, items, reset: true) replaces the client list (refiltering, pagination). limit: -50 keeps the last 50.
  • stream_delete(socket, :posts, post) needs the struct; with only a DOM id use stream_delete_by_dom_id/3.
  • Small, bounded lists (tabs, a few options) can stay plain assigns. Give the comprehension a :key so appending doesn't re-send every item:
<li :for={tag <- @tags} :key={tag.id}>{tag.name}</li>

:key has no effect on streams and isn't supported on slots.

Navigation

CallUse it for
push_patch(socket, to: ~p"/posts?page=2") / <.link patch={...}>Same LiveView, new params → handle_params/3 only
push_navigate(socket, to: ~p"/posts/#{post}") / <.link navigate={...}>Another LiveView in the same live_session, over the existing socket
redirect(socket, to: ~p"/users/log-in") / <.link href={...}>Full page load (controllers, other live_sessions, logout)

Assigns set before push_navigate are lost — the new LiveView mounts fresh. Flash survives.

Forms

Mirrors mix phx.gen.live's Form LiveView.

<.form for={@form} id="post-form" phx-change="validate" phx-submit="save">
  <.input field={@form[:title]} type="text" label="Title" phx-debounce="300" />
  <.input field={@form[:body]} type="textarea" label="Body" phx-debounce="blur" />
  <.button phx-disable-with="Saving..." variant="primary">Save Post</.button>
</.form>
@impl true
def mount(%{"id" => id}, _session, socket) do
  post = Blog.get_post!(socket.assigns.current_scope, id)

  {:ok,
   socket
   |> assign(:post, post)
   |> assign(:form, to_form(Blog.change_post(socket.assigns.current_scope, post)))}
end

@impl true
def handle_event("validate", %{"post" => post_params}, socket) do
  changeset = Blog.change_post(socket.assigns.current_scope, socket.assigns.post, post_params)
  {:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
end

def handle_event("save", %{"post" => post_params}, socket) do
  case Blog.update_post(socket.assigns.current_scope, socket.assigns.post, post_params) do
    {:ok, post} ->
      {:noreply,
       socket
       |> put_flash(:info, "Post updated")
       |> push_navigate(to: ~p"/posts/#{post}")}

    {:error, %Ecto.Changeset{} = changeset} ->
      {:noreply, assign(socket, :form, to_form(changeset))}
  end
end
  • Assign :form, not :changeset. Templates read @form[:field]; to_form/2 also accepts a plain map for schemaless forms: to_form(%{"q" => ""}, as: :search).
  • action: :validate is what makes errors show during phx-change; without an action the changeset's errors are hidden.
  • used_input?/1 hides errors on fields the user hasn't touched yet. The generated <.input> already calls it — call it yourself only in custom inputs.
  • Every form gets a unique id. Form recovery after a reconnect needs it, and LiveView 1.2 tests warn about phx-change forms without one.
  • phx-debounce="300" (ms) or "blur" on inputs that trigger server work; phx-throttle for rate-limiting clicks/keys.
  • Buttons go directly inside <.form>:
<.form for={@form} id="post-form" phx-submit="save">
  <.input field={@form[:title]} />
  <:actions>
    <.button>Save</.button>
  </:actions>
</.form>

That compiles with only a warning and renders no submit button. Phoenix 1.8 removed simple_form, which had that slot.

Async Loading

Each async task starts only when connected, runs in a linked process, and catches crashes into a :failed state.

@impl true
def mount(%{"id" => id}, _session, socket) do
  # Copy what the task needs out of the socket first. Referencing `socket`
  # inside the fn copies the whole socket into the task (LiveView warns).
  scope = socket.assigns.current_scope

  {:ok,
   socket
   |> assign(:post, Blog.get_post!(scope, id))
   |> assign_async(:stats, fn -> {:ok, %{stats: Analytics.post_stats(scope, id)}} end)
   |> stream_async(:comments, fn -> {:ok, Blog.list_comments(scope, id), limit: 50} end)}
end
<.async_result :let={stats} assign={@stats}>
  <:loading>Loading stats...</:loading>
  <:failed :let={_reason}>Couldn't load stats.</:failed>
  {stats.views} views
</.async_result>

<div id="comments" phx-update="stream">
  <p :for={{dom_id, comment} <- @streams.comments} id={dom_id}>{comment.body}</p>
</div>
<p :if={@comments.loading}>Loading comments...</p>
  • assign_async(socket, keys, fn) — the fn returns {:ok, %{key => value}} (every key listed) or {:error, reason}. The assign is a Phoenix.LiveView.AsyncResult (.ok?, .loading, .failed, .result).
  • stream_async(socket, :name, fn) — the fn returns {:ok, enumerable} or {:ok, enumerable, stream_opts}; @streams.name exists immediately and @name holds the AsyncResult.
  • start_async/3 + handle_async/3 — when you need to control the result (user-triggered work, replacing a running task):
alias Phoenix.LiveView.AsyncResult

@impl true
def handle_event("summarize", _params, socket) do
  %{current_scope: scope, post: post} = socket.assigns

  {:noreply,
   socket
   |> assign(:summary, AsyncResult.loading())
   |> start_async(:summary, fn -> Blog.summarize(scope, post) end)}
end

@impl true
def handle_async(:summary, {:ok, summary}, socket) do
  {:noreply, update(socket, :summary, &AsyncResult.ok(&1, summary))}
end

def handle_async(:summary, {:exit, reason}, socket) do
  {:noreply, update(socket, :summary, &AsyncResult.failed(&1, {:exit, reason}))}
end

A second start_async with the same name wins and the earlier result is ignored; cancel_async/3 kills one. In tests call render_async(view) before asserting.

Replaces this pattern, which still blocks the connected mount and has no error state:

socket =
  if connected?(socket),
    do: assign(socket, :stats, Analytics.post_stats(scope, id)),
    else: assign(socket, :stats, nil)

Function Components

attr :post, MyApp.Blog.Post, required: true
attr :compact, :boolean, default: false
attr :rest, :global
slot :inner_block
slot :footer

def post_card(assigns) do
  ~H"""
  <article class={["card", @compact && "card-sm"]} {@rest}>
    <h3>{@post.title}</h3>
    {render_slot(@inner_block)}
    <footer :if={@footer != []}>{render_slot(@footer)}</footer>
  </article>
  """
end

attr ..., default: replaces optional-assign lookups and gives compile-time warnings for missing or unknown attrs:

def post_card(assigns) do
  compact = Map.get(assigns, :compact, false)
  # ...
end

When a component must compute a derived assign, use assign/3 or assign_new/3 on assigns inside the component, not Map.put.

JS Commands and Hooks

Phoenix.LiveView.JS (aliased as JS in MyAppWeb's html_helpers) runs on the client with no round trip and survives DOM patches:

<button phx-click={JS.toggle(to: "#menu") |> JS.toggle_class("rotate-180", to: "#chevron")}>
  Menu
</button>
<div id="flash-banner" phx-mounted={JS.transition({"ease-out duration-300", "opacity-0", "opacity-100"})}>
  Saved
</div>
<dialog id="confirm" phx-mounted={JS.ignore_attributes("open")}>
  ...
</dialog>
  • Commands: push, show, hide, toggle, add_class, remove_class, toggle_class, set_attribute, remove_attribute, toggle_attribute, transition, dispatch, navigate, patch, focus, focus_first, push_focus, pop_focus, exec, ignore_attributes. Pipe them; JS.push("save") |> JS.hide(to: "#modal").
  • phx-mounted runs a command when the element is added to the DOM (page load or later patch).
  • JS.ignore_attributes/1 (LiveView 1.1+) stops the server from patching attributes the client owns, like <dialog open> or <details open>. It only ignores future server changes.
  • phx-click-away, phx-window-keydown (with phx-key), phx-blur/phx-focus cover most "small JS" needs before you write a hook.

Colocated hooks (LiveView 1.1+, Phoenix 1.8)

Write the hook next to the markup. The name starts with a dot and is namespaced to the module; Phoenix 1.8's app.js already spreads colocatedHooks into LiveSocket.

attr :field, Phoenix.HTML.FormField, required: true

def phone_input(assigns) do
  ~H"""
  <input type="text" id={@field.id} name={@field.name} value={@field.value} phx-hook=".PhoneMask" />
  <script :type={Phoenix.LiveView.ColocatedHook} name=".PhoneMask">
    export default {
      mounted() {
        this.el.addEventListener("input", () => {
          this.el.value = this.el.value.replace(/\D/g, "").slice(0, 10)
        })
      }
    }
  </script>
  """
end

Server ↔ hook events

# Server -> client: all hooks on the page can listen with this.handleEvent("chart:data", ...)
{:noreply, push_event(socket, "chart:data", %{points: points})}

# Client -> server: this.pushEvent("chart:clicked", %{index: 3}) arrives as an event;
# reply to the hook's promise with {:reply, map, socket}
@impl true
def handle_event("chart:clicked", %{"index" => index}, socket) do
  {:reply, %{label: Enum.at(socket.assigns.labels, index)}, socket}
end

A hook's element is patched by LiveView like any other; if the hook renders its own children, add phx-update="ignore" to it. Details, plus ColocatedJS for non-hook code and ColocatedCSS (1.2): JS interop reference.

Lifecycle Hooks: on_mount and attach_hook

on_mount runs before mount/3 — declared on a live_session in the router or with on_mount {MyAppWeb.UserAuth, :require_authenticated} in the module. It's where current_scope is assigned; see phoenix-liveview-auth.

attach_hook/4 taps into :handle_params, :handle_event, :handle_info, :handle_async or :after_render from an on_mount or mount. Return {:cont, socket} to continue or {:halt, socket} to stop the callback, and always add a catch-all clause:

def on_mount(:track_path, _params, _session, socket) do
  {:cont,
   attach_hook(socket, :current_path, :handle_params, fn _params, uri, socket ->
     {:cont, assign(socket, :current_path, URI.parse(uri).path)}
   end)}
end

Portals

<.portal> (LiveView 1.1+) renders its content into another DOM node — modals, tooltips and dropdowns that must escape overflow: hidden or a stacking context — while events still go to the current LiveView:

<.portal id="post-modal" target="body">
  <div class="modal modal-open">{@post.title}</div>
</.portal>

id and target (a unique CSS selector) are required. In tests, has_element?/2 can't see inside a portal; render element(view, "#post-modal") and match the HTML.

Debugging a Running LiveView

Phoenix.LiveView.Debug (LiveView 1.1+) inspects live processes from IEx:

Phoenix.LiveView.Debug.list_liveviews()
# => [%{pid: pid, view: MyAppWeb.PostLive.Index, topic: "lv:...", transport_pid: tpid}]
{:ok, socket} = Phoenix.LiveView.Debug.socket(pid)
socket.assigns
{:ok, components} = Phoenix.LiveView.Debug.live_components(pid)

Common Mistakes

MistakeFix
Blog.get_post!(id) / Repo.get(Post, id) in a LiveViewBlog.get_post!(socket.assigns.current_scope, id)
PubSub.subscribe in handle_paramsSubscribe in mount under connected?
List of records in an assign, update(socket, :posts, &[post | &1])stream_insert(socket, :posts, post, at: 0)
assign(socket, :changeset, cs) and <.form for={@changeset}>assign(socket, :form, to_form(cs))
Submit button inside an actions slot of <.form><.button> as a direct child
<.form> without idid="post-form"
socket.assigns.x inside an assign_async fnBind x = socket.assigns.x before the fn
if connected? around an expensive loadassign_async / stream_async
<%= @title %>, EEx for/if blocks{@title}, :for={...}, :if={...}
@current_user@current_scope (@current_scope.user) — Phoenix 1.8
push_navigate described as a reloadIt swaps LiveViews over the socket; redirect/2 reloads
Element with phx-hook and no idAdd a unique id (the client logs an error otherwise)

Phoenix PubSub Patterns

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Scope every topic to who may see the data. A global "posts" topic delivers every user's records to every subscriber. Use the 1.8 generator's shape, "user:#{scope.user.id}:posts", or the shared boundary ("org:#{scope.org.id}:posts") when data is shared.
  2. Wrap topics in context functions that take the scope — Blog.subscribe_posts(scope) and a private broadcast_post(scope, message). LiveViews never build topic strings.
  3. Broadcast from contexts, after the write succeeds. LiveViews only subscribe and react.
  4. Subscribe in mount/3 behind if connected?(socket). The disconnected render is a short-lived process. Subscribing in handle_params/3 adds a duplicate subscription on every push_patch.
  5. Handle PubSub messages in handle_info/2 and match the payload struct ({type, %Post{}} when type in [...]), as the generators do.
  6. Collections are streams. Re-stream with stream(socket, :posts, list_posts(scope), reset: true) (what phx.gen.live does), or apply one change with stream_insert/4 / stream_delete/3.
  7. Subscribing to a single record's topic needs a scoped load first — get_post!(scope, id) before subscribing to "post:#{post.id}".
  8. Test the full cycle: call the context with a scope, assert the LiveView re-rendered, and assert another user's change does not appear.

Context: scoped subscribe and broadcast

This is what mix phx.gen.live Blog Post posts ... generates in Phoenix 1.8:

defmodule MyApp.Blog do
  alias MyApp.Accounts.Scope
  alias MyApp.Blog.Post
  alias MyApp.Repo

  @doc """
  Subscribes to scoped notifications about post changes:
  `{:created, %Post{}}`, `{:updated, %Post{}}`, `{:deleted, %Post{}}`.
  """
  def subscribe_posts(%Scope{} = scope) do
    Phoenix.PubSub.subscribe(MyApp.PubSub, "user:#{scope.user.id}:posts")
  end

  defp broadcast_post(%Scope{} = scope, message) do
    Phoenix.PubSub.broadcast(MyApp.PubSub, "user:#{scope.user.id}:posts", message)
  end

  def list_posts(%Scope{} = scope), do: Repo.all_by(Post, user_id: scope.user.id)

  def create_post(%Scope{} = scope, attrs) do
    with {:ok, post = %Post{}} <-
           %Post{}
           |> Post.changeset(attrs, scope)
           |> Repo.insert() do
      broadcast_post(scope, {:created, post})
      {:ok, post}
    end
  end

  def update_post(%Scope{} = scope, %Post{} = post, attrs) do
    true = post.user_id == scope.user.id

    with {:ok, post = %Post{}} <-
           post
           |> Post.changeset(attrs, scope)
           |> Repo.update() do
      broadcast_post(scope, {:updated, post})
      {:ok, post}
    end
  end

  def delete_post(%Scope{} = scope, %Post{} = post) do
    true = post.user_id == scope.user.id

    with {:ok, post = %Post{}} <- Repo.delete(post) do
      broadcast_post(scope, {:deleted, post})
      {:ok, post}
    end
  end
end

If you broadcast inside Repo.transact/2, subscribers can receive the message before the commit and re-query stale data. Broadcast after transact returns {:ok, _}.


LiveView: subscribe in mount, update the stream

The generated index re-fetches through the subscriber's own scope and resets the stream. It's simple and always correct; it costs one query per event.

defmodule MyAppWeb.PostLive.Index do
  use MyAppWeb, :live_view

  alias MyApp.Blog

  @impl true
  def mount(_params, _session, socket) do
    if connected?(socket) do
      Blog.subscribe_posts(socket.assigns.current_scope)
    end

    {:ok,
     socket
     |> assign(:page_title, "Listing Posts")
     |> stream(:posts, Blog.list_posts(socket.assigns.current_scope))}
  end

  @impl true
  def handle_info({type, %MyApp.Blog.Post{}}, socket)
      when type in [:created, :updated, :deleted] do
    {:noreply,
     stream(socket, :posts, Blog.list_posts(socket.assigns.current_scope), reset: true)}
  end
end
<div id="posts" phx-update="stream">
  <div :for={{id, post} <- @streams.posts} id={id}>{post.title}</div>
</div>

For large lists, apply the single change instead of re-fetching:

@impl true
def handle_info({:created, %Post{} = post}, socket),
  do: {:noreply, stream_insert(socket, :posts, post, at: 0)}

def handle_info({:updated, %Post{} = post}, socket),
  do: {:noreply, stream_insert(socket, :posts, post)}

def handle_info({:deleted, %Post{} = post}, socket),
  do: {:noreply, stream_delete(socket, :posts, post)}

stream_insert/4 on an existing DOM id updates that item in place. Streams aren't kept in server memory, so there is no update(socket, :posts, ...) over a list to maintain.

Show page: match the record you're displaying

The topic carries all of the user's posts, so the show page pattern-matches on its own id and ignores the rest (generator show.ex):

@impl true
def handle_info({:updated, %Post{id: id} = post}, %{assigns: %{post: %{id: id}}} = socket) do
  {:noreply, assign(socket, :post, post)}
end

def handle_info({:deleted, %Post{id: id}}, %{assigns: %{post: %{id: id}}} = socket) do
  {:noreply,
   socket
   |> put_flash(:error, "The current post was deleted.")
   |> push_navigate(to: ~p"/posts")}
end

def handle_info({type, %Post{}}, socket) when type in [:created, :updated, :deleted] do
  {:noreply, socket}
end

Topic Naming

TopicWho may subscribe
"user:#{scope.user.id}:posts"that user (generator default)
"org:#{scope.org.id}:posts"members of the org, if your scope carries one
"post:#{post.id}:comments"only after get_post!(scope, id) succeeded for this user

The topic prefix is the scope's config entry name (user, org); see the phoenix-scopes-and-generators skill to add an org entry.

Topic names are not secrets, and Phoenix.PubSub.subscribe/2 has no access control. The only guard is that your code decides which topics a process subscribes to, after authorizing.

@impl true
def mount(%{"id" => id}, _session, socket) do
  # Raises (404) unless the post belongs to this scope.
  post = Blog.get_post!(socket.assigns.current_scope, id)

  if connected?(socket), do: Blog.subscribe_comments(post)

  {:ok, socket |> assign(:post, post) |> stream(:comments, Blog.list_comments(post))}
end

Broadcast Variants

FunctionDelivers to
Phoenix.PubSub.broadcast/3every subscriber on every node
Phoenix.PubSub.broadcast_from/4everyone except the given pid (skip the sender's own LiveView)
Phoenix.PubSub.local_broadcast/3subscribers on this node only
MyAppWeb.Endpoint.broadcast/3channel subscribers, wrapped in %Phoenix.Socket.Broadcast{}

Use local_broadcast when every node produces the event itself, such as per-node cache invalidation or Presence's handle_metas/4 callback; a cluster-wide broadcast would deliver it N times. For Presence in a LiveView, see below.


Presence in a LiveView

Generate MyAppWeb.Presence with mix phx.gen.presence and supervise it (see the phoenix-channels-essentials skill). Track the LiveView process itself and subscribe to the same topic. Presence diffs arrive as %Phoenix.Socket.Broadcast{event: "presence_diff"}:

@impl true
def mount(%{"id" => id}, _session, socket) do
  scope = socket.assigns.current_scope
  room = MyApp.Chat.get_room!(scope, id)
  topic = "room_presence:#{room.id}"

  if connected?(socket) do
    {:ok, _} = MyAppWeb.Presence.track(self(), topic, to_string(scope.user.id), %{email: scope.user.email})
    Phoenix.PubSub.subscribe(MyApp.PubSub, topic)
  end

  {:ok, socket |> assign(room: room, presence_topic: topic) |> assign_online()}
end

@impl true
def handle_info(%Phoenix.Socket.Broadcast{event: "presence_diff"}, socket) do
  {:noreply, assign_online(socket)}
end

defp assign_online(socket) do
  online =
    for {_user_id, %{metas: [meta | _]}} <- MyAppWeb.Presence.list(socket.assigns.presence_topic),
        do: meta.email

  assign(socket, :online, online)
end

The presence is removed when the LiveView process exits. Re-listing on each diff is fine for small rooms; for large ones apply joins/leaves from the diff payload to a stream.


Testing PubSub

describe "real-time updates" do
  setup :register_and_log_in_user

  test "a new post appears", %{conn: conn, scope: scope} do
    {:ok, lv, _html} = live(conn, ~p"/posts")

    post_fixture(scope, %{title: "New Post"})

    assert has_element?(lv, "#posts", "New Post")
  end

  test "a deleted post disappears", %{conn: conn, scope: scope} do
    post = post_fixture(scope, %{title: "To Delete"})
    {:ok, lv, _html} = live(conn, ~p"/posts")

    {:ok, _} = Blog.delete_post(scope, post)

    refute has_element?(lv, "#posts", "To Delete")
  end

  test "another user's post does not appear", %{conn: conn} do
    {:ok, lv, _html} = live(conn, ~p"/posts")

    post_fixture(user_scope_fixture(), %{title: "Not yours"})

    refute has_element?(lv, "#posts", "Not yours")
  end
end

Phoenix.PubSub.broadcast/3 puts the message in the LiveView's mailbox before it returns, and has_element?/3 (like render/1) is a call to that process, so the assertion sees the update without sleeping.

See the phoenix-liveview-essentials skill for LiveView lifecycle patterns and the testing-essentials skill before writing any _test.exs file.

Phoenix Scopes and Generators

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Check config :my_app, :scopes before generating. Generators read it at mix-task time; with no default entry (no phx.gen.auth yet) they silently emit unscoped contexts with no PubSub topic and no owner column. Run phx.gen.auth first, or add the entry.
  2. Take the default scope unless the data is truly global. --no-scope (lookup tables, public content) drops the scope argument, the owner column, the subscribe_*/broadcast_* functions and the cross-scope tests. --scope name only accepts a configured entry, and combining the two flags raises.
  3. Don't pass the owner as a field. With the default scope, user_id:references:users aborts the generator ("same name as the scope schema key"); the scope already adds field :user_id and the migration column.
  4. Keep the generated ownership checks. update_*, delete_* and change_* all start with true = post.user_id == scope.user.id. A hand-written "new" form must build %Post{user_id: scope.user.id}, or change_post/2 raises MatchError.
  5. Extend the one Scope struct; don't add a second assign. Add fields (org, org_role) plus a builder (put_org/3), and a second config entry that points at the same module and assign_key with a different access_path and schema_key.
  6. Fill extra scope fields with a plug and an on_mount hook. The plug covers the HTTP render and controllers; the hook covers the websocket mount and live navigation. Both look up membership through the current scope and never trust the slug alone.
  7. Write the test helpers before generating against a new entry. Generated tests call <name>_scope_fixture/0 from test_data_fixture and setup :<test_setup_helper>. Both must exist, and the setup helper must return scope:.
  8. Scoped controllers need a pipeline that assigns the scope. phx.gen.json output reads conn.assigns.current_scope, but the generated :api pipeline never sets it, so every action fails with KeyError.
  9. Pass the scope down; never rebuild it from params. Contexts pass it to other contexts. Background jobs store ids and rebuild it in perform/1.
  10. Adopt scopes in a pre-1.8 app in this order: Scope module, then config, then assign :current_scope, then test helpers, then owner columns, then generate or convert contexts one at a time.

The Two Pieces phx.gen.auth Adds

lib/my_app/accounts/scope.ex is a plain struct with for_user/1 (nil in gives nil out; guests have no scope). Its moduledoc asks you to extend it. The config entry tells every later generator how to use it:

config :my_app, :scopes,
  user: [
    default: true,
    module: MyApp.Accounts.Scope,
    assign_key: :current_scope,
    access_path: [:user, :id],
    schema_key: :user_id,
    schema_type: :id,
    schema_table: :users,
    test_data_fixture: MyApp.AccountsFixtures,
    test_setup_helper: :register_and_log_in_user
  ]

Keys accepted by Mix.Phoenix.Scope (an unknown key raises):

KeyDrives
defaultused when no flag is given; only one entry may be true (more raises)
modulethe struct pattern-matched in context heads (%Scope{} = scope)
assign_keysocket.assigns.current_scope / conn.assigns.current_scope in generated web code
access_paththe owner value: [:user, :id] becomes scope.user.id in queries, put_change and topics
schema_keythe owner field added to the schema and migration (:user_id)
schema_typethat field's type (:id, :binary_id)
schema_tablereferences(:users, on_delete: :delete_all); nil gives a plain column with no FK
schema_migration_typeoverrides the migration column type (defaults to schema_type unless it is :id)
route_prefixe.g. "/orgs/:org_slug", prepended to every generated path; at most one :param
route_access_pathwhat fills that param, e.g. [:org, :slug] (defaults to access_path minus its last element)
test_data_fixturethe module generated tests import <name>_scope_fixture/0 from
test_setup_helperthe setup :helper in generated LiveView and controller tests

The entry name (user, org) is also the PubSub topic prefix ("user:#{key}:posts") and the changeset's argument name (user_scope). The config must be in config/config.exs (or a file it imports). Generators never load runtime.exs.

phx.gen.auth takes --scope name and --assign-key key to rename its entry. It marks the entry default: true only if no default exists yet.


Running the Generators

CommandResult
mix phx.gen.live Blog Post posts title:stringdefault scope
mix phx.gen.live Projects Project projects name:string --scope orgthe org entry
mix phx.gen.html Pages Page pages title:string --no-scopeunscoped
--scope missing** (Mix) Scope :missing not configured!

phx.gen.live, phx.gen.html, phx.gen.json, phx.gen.context and phx.gen.schema all take --scope / --no-scope.

A scoped run changes these files:

  • Schema: field :user_id, :id (not belongs_to) and changeset(post, attrs, user_scope), which casts only your fields and ends with put_change(:user_id, user_scope.user.id).
  • Migration: add :user_id, references(:users, on_delete: :delete_all) and create index(:posts, [:user_id]).
  • Context: every function takes %Scope{} first. list_* uses Repo.all_by(Post, user_id: ...) and get_*! uses Repo.get_by!(Post, id: id, user_id: ...). Writes assert ownership and broadcast {:created | :updated | :deleted, post} on "user:#{scope.user.id}:posts" (the full module is in the phoenix-pubsub-patterns skill).
  • LiveViews and controllers: every context call passes socket.assigns.current_scope, and layouts get current_scope={@current_scope}. The router hint ends with "Ensure the routes are defined in a block that sets the :current_scope assign".
  • Tests and fixtures: post_fixture(scope, attrs \\ %{}) and setup :register_and_log_in_user. Context tests create posts under two user_scope_fixture() scopes and assert that get_post!(other_scope, id) raises Ecto.NoResultsError.

Put generated LiveView routes in the existing authenticated live_session (see the phoenix-liveview-auth skill).


Adding an Org to the Scope

The plumbing for org-owned data. Roles, policies and who may do what are covered in the phoenix-authorization-patterns skill.

1. Struct and builder

defmodule MyApp.Accounts.Scope do
  alias MyApp.Accounts.User
  alias MyApp.Orgs.Org

  defstruct user: nil, org: nil, org_role: nil

  def for_user(%User{} = user), do: %__MODULE__{user: user}
  def for_user(nil), do: nil

  def put_org(%__MODULE__{} = scope, %Org{} = org, role) do
    %{scope | org: org, org_role: role}
  end
end

2. A second config entry for the generators

config :my_app, :scopes,
  user: [
    default: true,
    # ... unchanged
  ],
  org: [
    module: MyApp.Accounts.Scope,
    assign_key: :current_scope,
    access_path: [:org, :id],
    route_prefix: "/orgs/:org_slug",
    route_access_path: [:org, :slug],
    schema_key: :org_id,
    schema_type: :id,
    schema_table: :orgs,
    test_data_fixture: MyApp.AccountsFixtures,
    test_setup_helper: :register_and_log_in_user_with_org
  ]

3. Fill it: plug + on_mount

defmodule MyAppWeb.OrgScope do
  use MyAppWeb, :verified_routes

  import Plug.Conn

  alias MyApp.Accounts.Scope
  alias MyApp.Orgs

  # Plug: the HTTP render and controllers
  def assign_org(conn, _opts) do
    scope = conn.assigns.current_scope

    # {org, role} if the scope's user is a member, else nil
    case Orgs.get_membership(scope, conn.params["org_slug"]) do
      {org, role} ->
        assign(conn, :current_scope, Scope.put_org(scope, org, role))

      nil ->
        conn
        |> Phoenix.Controller.put_flash(:error, "Organization not found.")
        |> Phoenix.Controller.redirect(to: ~p"/")
        |> halt()
    end
  end

  # on_mount: the websocket mount and each live navigation into the session
  def on_mount(:assign_org, %{"org_slug" => slug}, _session, socket) do
    scope = socket.assigns.current_scope

    case Orgs.get_membership(scope, slug) do
      {org, role} ->
        {:cont, Phoenix.Component.assign(socket, :current_scope, Scope.put_org(scope, org, role))}

      nil ->
        {:halt,
         socket
         |> Phoenix.LiveView.put_flash(:error, "Organization not found.")
         |> Phoenix.LiveView.redirect(to: ~p"/")}
    end
  end
end
# router.ex — add `import MyAppWeb.OrgScope, only: [assign_org: 2]`
scope "/orgs/:org_slug", MyAppWeb do
  pipe_through [:browser, :require_authenticated_user, :assign_org]

  live_session :require_org_member,
    on_mount: [{MyAppWeb.UserAuth, :require_authenticated}, {MyAppWeb.OrgScope, :assign_org}] do
    live "/projects", ProjectLive.Index, :index
    live "/projects/new", ProjectLive.Form, :new
    live "/projects/:id", ProjectLive.Show, :show
    live "/projects/:id/edit", ProjectLive.Form, :edit
  end
end

The plug runs after :require_authenticated_user, so current_scope.user is always set. The hook runs on every mount, but a push_patch to another org's URL inside the same LiveView does not re-run it. Generated code never patches across orgs; if yours does, re-check the org in handle_params/3.

4. Test helpers (before generating)

# test/support/fixtures/accounts_fixtures.ex
def org_scope_fixture, do: org_scope_fixture(user_scope_fixture())

def org_scope_fixture(%Scope{} = user_scope) do
  n = System.unique_integer([:positive])
  {:ok, org} = MyApp.Orgs.create_org_for(user_scope, %{name: "Org #{n}", slug: "org-#{n}"})
  Scope.put_org(user_scope, org, :admin)
end
# test/support/conn_case.ex
def register_and_log_in_user_with_org(context) do
  %{scope: scope} = context = register_and_log_in_user(context)
  Map.put(context, :scope, MyApp.AccountsFixtures.org_scope_fixture(scope))
end

5. Generate

mix phx.gen.live Projects Project projects name:string --scope org produces:

  • field :org_id, :id and put_change(:org_id, org_scope.org.id);
  • the topic "org:#{scope.org.id}:projects", shared by every member;
  • routes ~p"/orgs/#{@current_scope.org.slug}/projects";
  • the new form building %Project{org_id: socket.assigns.current_scope.org.id};
  • tests using org_scope_fixture() and setup :register_and_log_in_user_with_org.

It stores no user_id, because the org owns the row. To record the author as well, add a non-cast field :created_by_id, :id and put_change(:created_by_id, scope.user.id) in the changeset.

Calling an org-scoped function with a user-only scope crashes deep inside with BadMapError (scope.org is nil). For a clear failure at the call site, tighten the head to %Scope{org: %Org{}} = scope.


Threading the Scope

  • Hand-written context functions follow the generated shape: scope first, owner filter in the query, ownership assert before writes. The rules are in the ecto-essentials skill.
  • Context calling context: pass the same scope (Billing.charge(scope, ...)), never scope.user or a bare id.
  • Background jobs: a scope isn't JSON. Enqueue ids and rebuild the scope in the worker.
@impl Oban.Worker
def perform(%Oban.Job{args: %{"user_id" => user_id, "post_id" => post_id}}) do
  scope = MyApp.Accounts.Scope.for_user(MyApp.Accounts.get_user!(user_id))
  post = MyApp.Blog.get_post!(scope, post_id)
  MyApp.Blog.publish_post(scope, post)
end

Scoped JSON Endpoints

The generated JSON controller test uses setup :register_and_log_in_user, which logs in through the session. Behind a Bearer-token pipeline, those tests fail until you swap that setup for a helper that creates a token and sets the authorization header. The token plug that assigns :current_scope is in the phoenix-json-api skill.


Adopting Scopes in a Pre-1.8 App

A 1.7 phx.gen.auth app assigns :current_user (fetch_current_user, on_mount :mount_current_user, :ensure_authenticated), and its register_and_log_in_user returns no scope. After bumping to Phoenix 1.8:

  1. Scope module. Copy the 1.8 accounts/scope.ex (above, without the org fields).
  2. Config. Add the :scopes entry shown at the top (default: true, your fixture module, your setup helper name).
  3. Assign :current_scope next to :current_user. Keep both until every caller has moved:
def fetch_current_user(conn, _opts) do
  {user_token, conn} = ensure_user_token(conn)
  user = user_token && Accounts.get_user_by_session_token(user_token)

  conn
  |> assign(:current_user, user)
  |> assign(:current_scope, Scope.for_user(user))
end

defp mount_current_user(socket, session) do
  socket
  |> Phoenix.Component.assign_new(:current_user, fn ->
    if user_token = session["user_token"] do
      Accounts.get_user_by_session_token(user_token)
    end
  end)
  |> Phoenix.Component.assign_new(:current_scope, fn %{current_user: user} ->
    Scope.for_user(user)
  end)
end
  1. Test helpers. Add user_scope_fixture/0 to AccountsFixtures, and have register_and_log_in_user/1 return scope: Scope.for_user(user) too.
  2. Owner columns. Add user_id (FK and index) to existing tables, backfill it, then make it NOT NULL before scoping their contexts. On tables with live traffic, follow the steps in the ecto-migrations-safety skill.
  3. Convert contexts one at a time. Add the scope argument and the owner filter. The arity change makes the compiler list every caller you still have to fix.
  4. Web layer. 1.8 templates render <Layouts.app flash={@flash} current_scope={@current_scope}> and use 1.8 components (<.button variant="primary">). A 1.7 app has neither: its app.html.heex is a layout using {@inner_content}, and its button/1 has no :variant. Port the 1.8 Layouts.app/1 and core_components.ex first, or generate into a scratch 1.8 app and copy over only the context, schema, migration and tests.

Common Mistakes

# Bad — unscoped calls and a global topic in a scoped app
posts = Blog.list_posts()
post = Repo.get!(Post, id)
Phoenix.PubSub.broadcast(MyApp.PubSub, "posts", {:updated, post})

def update_post(%Scope{} = _scope, %Post{} = post, attrs) do
  post |> Post.changeset(attrs) |> Repo.update()
end
# Good — scope in, owner filter in the query, ownership asserted, scoped topic
posts = Blog.list_posts(scope)
post = Blog.get_post!(scope, id)

def update_post(%Scope{} = scope, %Post{} = post, attrs) do
  true = post.user_id == scope.user.id

  with {:ok, post = %Post{}} <- post |> Post.changeset(attrs, scope) |> Repo.update() do
    broadcast_post(scope, {:updated, post})
    {:ok, post}
  end
end
SymptomCause
Generated context has no scope argumentno default :scopes entry, or --no-scope
KeyError :current_scope in a generated controllerits pipeline doesn't assign the scope (:api)
undefined function org_scope_fixture/0 in generated teststhe helper for the new entry wasn't written first
MatchError opening a "new" formstruct built without the owner (%Post{} instead of %Post{user_id: ...})
Another user's records appear livea global topic, or a hand-written broadcast that skips broadcast_*
There can only be one default scopetwo entries have default: true (often a copy-pasted user entry)

See the testing-essentials skill for the generated fixtures in tests, and the phoenix-authorization-patterns skill for policies and roles on top of the scope.

Phoenix UI: Tailwind v4, daisyUI and core_components

Verified against Phoenix 1.8, LiveView 1.2, Tailwind 4.3, daisyUI 5.5 — October 2026

RULES — Follow these with no exceptions

  1. Wrap every page in <Layouts.app flash={@flash}>, and pass current_scope={@current_scope} when the app has auth. In 1.8 the app layout is a function component that you call from the template; it is not applied automatically. It already renders the flash group, so don't render a second one.
  2. Tailwind is configured in assets/css/app.css. There is no tailwind.config.js. Keep @import "tailwindcss" source(none), and add an @source line for every directory outside lib/my_app_web that contains class names. Tailwind scans only the listed paths.
  3. Write every class name as a complete literal. "text-#{color}-500" produces no CSS. Map values to full strings (%{error: "badge-error"}) or use function clauses. Safelist with @source inline("...") only when the values really come from data.
  4. Use daisyUI's semantic colors rather than raw palette colors. Write bg-base-100, text-base-content, btn-primary, text-error and the *-content pairs, not bg-white, text-gray-900 or text-red-600. The semantic colors switch with the light/dark theme; hard-coded colors don't.
  5. Use core_components.ex first, and extend it rather than writing one-off markup. To get a new look, add a variant, an attr or a new component in that module, and keep its attr/slot declarations, including values: and required:.
  6. Passing class to <.button> or <.input> replaces the default classes; it doesn't add to them. <.button class="w-full"> loses btn. Pass the full class list (class="btn btn-primary w-full") or add a variant.
  7. Icons are <.icon name="hero-…"> with a literal name. The suffixes are none (outline 24), -solid, -mini and -micro. icon/1 accepts only name and class; any other attribute is a compile warning and isn't rendered.
  8. <.button> declares only href navigate patch method download name value disabled. type="button" (which you need for a non-submitting button inside a form) is an "undefined attribute" warning, and that warning fails mix precommit (compile --warnings-as-errors). Add type to the button's include: list.
  9. Accessibility you add yourself: a label on every <.input> (a placeholder is not a label), an aria-label on every icon-only button, <button> or <.link> for anything clickable (never phx-click on a div), and <.focus_wrap> around modal content.

Related skills: phoenix-liveview-essentials covers forms with to_form, streams, JS commands and colocated hooks. deployment-gotchas covers assets.deploy and the digest in releases.


What the generator sets up

PieceWhereWhat it is
Tailwind CLI{:tailwind, "~> 0.5"} in mix.exs; config :tailwind, version: "4.3.3", my_app: [...] in config/config.exsA standalone binary (no Node) that mix tailwind.install downloads to _build/tailwind-<target>-<version>
daisyUI{:daisyui, github: "saadeghi/daisyui", tag: "v5.5.20", sparse: "packages/bundle", app: false, compile: false} in mix.exsA git dep that lands in deps/daisyui/packages/bundle/; there is no npm
Heroicons{:heroicons, github: "tailwindlabs/heroicons", tag: "v2.2.0", sparse: "optimized", ...}SVGs in deps/heroicons/optimized, turned into hero-* classes by assets/vendor/heroicons.js
Entry CSSassets/css/app.cssAll Tailwind and daisyUI configuration
Dev watchertailwind: {Tailwind, :install_and_run, [:my_app, ~w(--watch)]} in config/dev.exsRebuilds on save
Aliasesassets.setup, assets.build (compile, tailwind my_app, esbuild my_app), assets.deploy (tailwind my_app --minify, esbuild my_app --minify, phx.digest)

@plugin "daisyui/packages/bundle/daisyui" resolves because the tailwind profile sets env: %{"NODE_PATH" => [Path.expand("../deps", __DIR__), Mix.Project.build_path()]}, so bare imports are looked up in deps/ and _build/<env>/. To upgrade daisyUI, bump the tag: and run mix deps.update daisyui. To upgrade Tailwind, bump version: in config.exs and run mix tailwind.install. Apps generated by earlier 1.8.x releases may vendor the plugin as assets/vendor/daisyui.js and daisyui-theme.js and point @plugin at ../vendor/... instead. Check which form your app uses before you edit anything.

app.css, annotated

@import "tailwindcss" source(none);            /* turn OFF automatic source detection */
@import "phoenix-colocated/my_app/colocated.css";  /* LiveView ColocatedCSS output (in _build) */
@source "../css";
@source "../js";                               /* classes toggled from JS */
@source "../../lib/my_app_web";                /* every HEEx template and component */
@source "../../_build/dev/phoenix-colocated/my_app/*/";  /* dev reload of colocated CSS */

@plugin "../vendor/heroicons";                 /* hero-* classes */
@plugin "daisyui/packages/bundle/daisyui" { themes: false; }   /* components, no built-in themes */
@plugin "daisyui/packages/bundle/daisyui-theme" { name: "dark"; prefersdark: true; /* --color-* */ }
@plugin "daisyui/packages/bundle/daisyui-theme" { name: "light"; default: true; /* --color-* */ }

@custom-variant phx-click-loading (.phx-click-loading&, .phx-click-loading &);
@custom-variant phx-submit-loading (.phx-submit-loading&, .phx-submit-loading &);
@custom-variant phx-change-loading (.phx-change-loading&, .phx-change-loading &);
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
  • Why the @source list matters: source(none) means Tailwind scans exactly these paths and nothing else. Classes that live in lib/my_app/ (for example, a helper module that returns class strings), in a component library under deps/, or in a sibling umbrella app produce no CSS until you add a line for them. Write it relative to app.css, as in @source "../../deps/my_ui_kit/lib";. Don't drop source(none) to "fix" this: automatic detection starts from the project root.
  • Don't delete the phoenix-colocated import. The file exists only after mix compile. That is why assets.build starts with compile, and why the release Dockerfile runs mix compile before mix assets.deploy. If you run mix tailwind my_app on a fresh checkout, it fails with Can't resolve 'phoenix-colocated/my_app/colocated.css'.
  • The loading variants style elements while an event is in flight: <.button class="btn btn-primary phx-submit-loading:opacity-60">.
  • dark: follows data-theme="dark", not prefers-color-scheme. The theme script sets that attribute for system-dark users too, so dark: works in both cases, but semantic daisyUI colors usually make dark: unnecessary.
  • To add your own CSS, use plain rules or @layer components { ... } below the generated block.

Dynamic class names

Tailwind reads the source files as plain text and generates CSS only for complete class tokens it finds. It never evaluates Elixir.

<span class={"badge badge-#{@status}"}>{@status}</span>
<div class={"text-#{@color}-600"}>...</div>

Neither badge-published nor text-teal-600 ends up in the built CSS (verified with Tailwind 4.3.3). The markup ships unstyled, and nothing warns you.

defmodule MyAppWeb.StatusComponents do
  use Phoenix.Component

  # Full class names written out, so the scanner sees every one.
  @status_classes %{
    draft: "badge-ghost",
    published: "badge-success",
    archived: "badge-neutral"
  }

  attr :status, :atom, required: true, values: Map.keys(@status_classes)

  def status_badge(assigns) do
    assigns = assign(assigns, :status_class, Map.fetch!(@status_classes, assigns.status))

    ~H"""
    <span class={["badge", @status_class]}>{Phoenix.Naming.humanize(@status)}</span>
    """
  end
end
  • Conditional classes use the list form: class={["btn", @active && "btn-active", @size == :sm && "btn-sm"]}. false and nil entries are dropped.
  • Icon names follow the same rule: name={"hero-#{@icon}"} generates nothing unless that exact hero-… string also appears somewhere in the scanned sources. Map to full names.
  • When the values really come from data (user-chosen colors stored in the DB), safelist them in app.css with @source inline("text-{red,green,blue}-600");. Brace expansion is supported. For arbitrary values, validate them (for example against ~r/\A#[0-9a-f]{6}\z/i) and set a CSS variable, style={"--accent: #{@hex}"}, that a class like bg-(--accent) reads.

daisyUI themes and dark mode

The generated app ships two custom themes, defined in app.css with the daisyui-theme plugin. light has default: true and dark has prefersdark: true. All built-in daisyUI themes are disabled by themes: false. Each theme is a set of --color-* variables (base-100/200/300, base-content, primary, primary-content, secondary, accent, neutral, info, success, warning, error, each with a -content pair), plus radius, size, border and depth tokens. To restyle the app, edit those variables, not the components.

How the toggle works (in root.html.heex and Layouts.theme_toggle/1):

  • An inline script in <head> sets data-theme on <html> before first paint. It reads localStorage["phx:theme"] and falls back to "system", which follows prefers-color-scheme. It also sets data-theme-source="system" or "user".
  • Each toggle button is phx-click={JS.dispatch("phx:set-theme")} with a data-phx-theme="system|light|dark" attribute. The script listens for phx:set-theme and reads e.target.dataset.phxTheme.
  • The script returns early if <html> already has data-theme. To use a theme stored on the user, render it from the server in root.html.heex: <html lang="en" data-theme={@current_scope && @current_scope.user.theme}>, where theme is a field you add to the user and is nil for "system". A nil value omits the attribute, so the script takes over.
  • To add a theme, either add another @plugin "daisyui/packages/bundle/daisyui-theme" { name: "brand"; ... } block or enable a built-in one (themes: corporate;), then add a button with data-phx-theme="brand". Don't enable the built-in light/dark themes; their names collide with the custom ones. dark: utilities only match a theme named dark.

Semantic classes to reach for:

NeeddaisyUI classes
Page and surfacesbg-base-100 (page), bg-base-200 / bg-base-300 (raised or sunken), text-base-content, text-base-content/70 (muted)
Brand and status colorsbg-primary text-primary-content, text-error, bg-success text-success-content (always pair a background with its -content color)
Buttonsbtn + btn-primary / btn-error / btn-ghost / btn-outline / btn-soft; sizes btn-sm, shapes btn-square, btn-circle
Form controlsinput, select, textarea, checkbox, toggle, fieldset, label; error state input-error / select-error / textarea-error
Feedbackalert + alert-info / alert-success / alert-warning / alert-error, badge badge-*, loading loading-spinner, toast, skeleton
Layout and datacard card-body card-title card-actions, navbar, menu, table table-zebra, list list-row, tabs tab tab-active, modal modal-box modal-action, dropdown, join, divider, stat

If the project's AGENTS.md says to hand-write Tailwind components instead of using daisyUI components (the 1.8 generator writes that line), follow it for components. Keep using the semantic color tokens anyway, because they are what makes dark mode work.

core_components and Layouts

ComponentKey attrs and slotsNotes
<Layouts.app>flash (required), current_scope (default nil), inner blockLayouts is aliased in html_helpers. It renders the navbar, <main> and <.flash_group>
<.input>field={@form[:x]}, type, label, options + prompt (select), multiple, class, error_class, errors; global :rest takes aria-*, phx-*, data-* and the listed HTML attrsShows field.errors only when used_input?(field) is true. Translates errors via translate_error/1. Types: text-likes, select, textarea, checkbox, hidden; radio is not supported
<.button>variant (values: ~w(primary); default is btn-primary btn-soft), class, navigate/patch/hrefRenders <.link> when given navigate/patch/href, otherwise <button>
<.icon>name (hero-* only), class (default "size-4")Renders an empty <span> styled with a CSS mask, so color is currentColor and the size comes from size-*
<.header>inner block (the <h1>), subtitle slot, actions slotEach <.header> renders an <h1>, so use one per page
<.table>id, rows (list or @streams.x), row_click, row_id, row_item; col slot with label, action slotGiven a stream, it sets phx-update="stream" and derives row_id for you
<.list>item slot with titleRead-only detail view
<.flash>kind (:info / :error), flash, title<.flash_group> lives in Layouts and renders only :info and :error. A put_flash(socket, :warning, ...) never shows unless you add a kind

A generated-style page, using a stream and a form:

<Layouts.app flash={@flash} current_scope={@current_scope}>
  <.header>
    Listing Posts
    <:subtitle>Everything you've written.</:subtitle>
  </.header>

  <.table
    id="posts"
    rows={@streams.posts}
    row_click={fn {_id, post} -> JS.navigate(~p"/posts/#{post}") end}
  >
    <:col :let={{_id, post}} label="Title">{post.title}</:col>
    <:col :let={{_id, post}} label="Status"><.status_badge status={post.status} /></:col>
    <:action :let={{_id, post}}>
      <.link navigate={~p"/posts/#{post}/edit"}>Edit</.link>
    </:action>
  </.table>

  <.form for={@form} id="post-form" phx-change="validate" phx-submit="save">
    <.input field={@form[:title]} type="text" label="Title" />
    <.input field={@form[:status]} type="select" label="Status" options={@status_options} prompt="Choose…" />
    <.input field={@form[:published]} type="checkbox" label="Published" />
    <.button phx-disable-with="Saving..." variant="primary">Save</.button>
  </.form>
</Layouts.app>

The generated index also puts a New Post <.button variant="primary" navigate={...}> in the header's actions slot. For the form's LiveView side (to_form, validate, errors), see the phoenix-liveview-essentials skill.

Extending core_components

Edit lib/my_app_web/components/core_components.ex directly. It is your code, not a dependency. These three changes cover most needs.

More button variants, plus type. Keep the map of full class strings (rule 3) and keep values: in sync, so a typo like variant="dangr" is a compile-time warning:

attr :rest, :global, include: ~w(href navigate patch method download name value disabled type)
attr :class, :any
attr :variant, :string, values: ~w(primary danger ghost)
slot :inner_block, required: true

def button(%{rest: rest} = assigns) do
  variants = %{
    "primary" => "btn-primary",
    "danger" => "btn-error",
    "ghost" => "btn-ghost",
    nil => "btn-primary btn-soft"
  }

  assigns =
    assign_new(assigns, :class, fn ->
      ["btn", Map.fetch!(variants, assigns[:variant])]
    end)

  if rest[:href] || rest[:navigate] || rest[:patch] do
    ~H"""
    <.link class={@class} {@rest}>{render_slot(@inner_block)}</.link>
    """
  else
    ~H"""
    <button class={@class} {@rest}>{render_slot(@inner_block)}</button>
    """
  end
end

Errors that screen readers announce. The generated <.input> wraps the control in its <label>, so the label is announced. The error <p> isn't connected to the field, though. In the catch-all text-input clause, change the <input> and the error list like this (and do the same in the select and textarea clauses):

<input
  type={@type}
  name={@name}
  id={@id}
  value={Phoenix.HTML.Form.normalize_value(@type, @value)}
  class={[@class || "w-full input", @errors != [] && (@error_class || "input-error")]}
  aria-invalid={@errors != [] && "true"}
  aria-describedby={@errors != [] && "#{@id}-errors"}
  {@rest}
/>
<div :if={@errors != []} id={"#{@id}-errors"}>
  <.error :for={msg <- @errors}>{msg}</.error>
</div>

A false attribute value is omitted from the rendered HTML. This relies on @id, which field= always provides; when you use name= without field=, pass an id too.

A new flash kind. Add :warning to flash/1's values:, add an @kind == :warning && "alert-warning" entry to its class list, and add <.flash kind={:warning} flash={@flash} /> to Layouts.flash_group/1.

For a brand-new component, put it in core_components.ex (or in a new module under components/ that you import in html_helpers). Give it attr/slot declarations with doc:, and a :global rest attr so callers can pass id, aria-* and phx-*.

Accessibility: what you get vs. what's on you

Already done by the generated codeOn you
<.input> wraps the control in its <label for=...>Always pass label, or aria-label when the visual design has none. A placeholder disappears on input and isn't a reliable name
<.flash> has role="alert"; flash_group is aria-live="polite"; the close button has aria-labelName icon-only buttons: <.button navigate={~p"/posts"} aria-label="Back to posts"><.icon name="hero-arrow-left" /></.button>. The generated show.ex back button and the three theme_toggle buttons have no name, so add one
<.table> has a sr-only "Actions" header; the generated index keeps a sr-only Show link because row_click puts phx-click on <td>, which a keyboard can't reachKeep a real <.link> in every clickable row. Never put phx-click on a div/span without also adding role, tabindex and key handling; use <button type="button"> instead
Decorative arrows in the layout use aria-hidden="true"Radio groups (<.input> doesn't render radios): write <fieldset><legend>…</legend> with a <label> per <input type="radio">
Modals and menus: wrap the content in <.focus_wrap id="…"> (from Phoenix.Component), save focus with JS.push_focus(), move it in with JS.focus_first(to: "#…"), restore it with JS.pop_focus(), or use a native <dialog class="modal">. 1.8's core_components has no modal
Contrast: pair every bg-<color> with its text-<color>-content, and check custom theme variables in both themes
Respect reduced motion: motion-safe:animate-spin, as the generated flash does

Common mistakes

WrongRight
A tailwind.config.js with content: [...]@source lines in app.css (Tailwind v4 ignores the JS config unless you load it with @config)
Component classes defined in lib/my_app/ui.ex and missing in the browserAdd @source "../../lib/my_app/ui.ex"; (or the directory)
class={"bg-#{@color}-500"}A map or function returning "bg-red-500" etc., or @source inline(...)
bg-white text-gray-900 on cardsbg-base-100 text-base-content (works in dark mode)
<.button class="w-full"><.button class="btn btn-primary w-full">, or a variant
<.button type="button"> warning breaking mix precommitAdd type to include: in button/1
<.icon name="hero-x-mark" aria-hidden="true" /> (warns; attribute dropped)It's an empty span, so nothing to hide. Name the button instead
A second <.flash_group> inside a page already wrapped in Layouts.appOne per page. A second group shows every flash twice and duplicates the flash-group / client-error / server-error ids
Forgetting flash={@flash} on <Layouts.app>flash is required: true on app/1. Leaving it out is a compile warning, and the layout has nothing to render flashes from
Running mix tailwind my_app in CI before compilingmix assets.build (compiles first) or mix compile && mix assets.deploy
An empty phx-update="stream" container with no messageAdd <div id="posts-empty" class="hidden only:block">No posts yet</div> as the first child (every child of a stream container needs an id)

Phoenix File Uploads

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Never take the stored extension or the served content type from the client. LiveView accepts an entry when its client MIME type or its file extension matches :accept, so x.html sent as image/png passes. Sniff the magic bytes of the uploaded file and pick the extension from an allowlist keyed on the detected type.
  2. Name files on the server — Ecto.UUID.generate() <> allowlisted_ext. Never put entry.client_name (or any request param) in a path.
  3. Store under a configured directory, not a cwd-relative "priv/static/uploads". priv/static is replaced on every release deploy and runtime files are never in the digest manifest. Read the directory from app config at runtime and serve it with its own Plug.Static (or use object storage via :external).
  4. Private files go through a controller that loads the record through the scope — Media.get_document!(scope, id). Never accept a filename or path from the request. Send an allowlisted content_type, disposition: :attachment and x-content-type-options: nosniff.
  5. The consume_uploaded_entries/3 callback must return {:ok, value} or {:postpone, value}. Wrap the context result ({:ok, Media.create_image(...)}) and handle failures after consuming.
  6. Render upload_errors/1 and upload_errors/2, and make error_to_string/1 total — atoms, {:external_metadata_failure, _}, {:writer_failure, _}, your validator: reasons, and a catch-all.
  7. Form markup is Phoenix 1.8: assign :form in mount, give <.form> an id, put <.button> directly inside it (<.form> has no actions slot), and use a plain <label for={@uploads.images.ref}> (1.8 core_components has no label/1 component).
  8. Default to manual uploads. With auto_upload: true, consume_uploaded_entries/3 raises while any entry is still in progress; consume from a progress: callback once entry.done?.
  9. External uploads need both halves: the :external function returns meta with an :uploader name, and that name must be registered in uploaders: on the JS LiveSocket.

Complete Upload Pattern (local storage)

Context: sniff, name, store

The MyApp.Media.Image schema is the one in the ecto-essentials skill: title, filename (server-generated), original_name (display only), content_type, byte_size, folder_id, user_id. Its changeset/3 casts only [:title, :original_name].

defmodule MyApp.Media do
  alias MyApp.Accounts.Scope
  alias MyApp.Media.Image
  alias MyApp.Repo

  # Detected content type => extension we store under. The client's name and
  # type never decide either.
  @exts %{"image/jpeg" => ".jpg", "image/png" => ".png", "image/webp" => ".webp"}

  def allowed_type?(content_type), do: Map.has_key?(@exts, content_type)

  def create_image(%Scope{} = scope, tmp_path, attrs) do
    with {:ok, stored} <- store_file(tmp_path) do
      # Storage fields are set on the struct, never cast from attrs.
      changeset = Image |> struct!(stored) |> Image.changeset(attrs, scope)

      case Repo.insert(changeset) do
        {:ok, image} ->
          {:ok, image}

        {:error, changeset} ->
          # Don't leave an orphaned file behind a failed insert.
          remove_file(stored.filename)
          {:error, changeset}
      end
    end
  end

  def delete_image(%Scope{} = scope, %Image{} = image) do
    true = image.user_id == scope.user.id

    with {:ok, image} <- Repo.delete(image) do
      remove_file(image.filename)
      {:ok, image}
    end
  end

  # list_images/2, get_image!/2, update_image/3: see the ecto-essentials skill.

  def image_url(%Image{filename: filename}), do: "/uploads/" <> filename

  # Resolved at runtime, so prod can point at a mounted volume (config/runtime.exs).
  def uploads_dir, do: Application.fetch_env!(:my_app, :uploads_dir)

  defp store_file(tmp_path) do
    with {:ok, content_type} <- sniff_image(tmp_path) do
      filename = Ecto.UUID.generate() <> Map.fetch!(@exts, content_type)
      File.mkdir_p!(uploads_dir())
      File.cp!(tmp_path, Path.join(uploads_dir(), filename))

      {:ok, %{filename: filename, content_type: content_type, byte_size: File.stat!(tmp_path).size}}
    end
  end

  defp remove_file(filename), do: File.rm(Path.join(uploads_dir(), filename))

  # Magic bytes from the file itself.
  defp sniff_image(path) do
    case File.open(path, [:read, :binary], &IO.binread(&1, 12)) do
      {:ok, <<0x89, "PNG", 0x0D, 0x0A, 0x1A, 0x0A, _::binary>>} -> {:ok, "image/png"}
      {:ok, <<0xFF, 0xD8, 0xFF, _::binary>>} -> {:ok, "image/jpeg"}
      {:ok, <<"RIFF", _::binary-size(4), "WEBP", _::binary>>} -> {:ok, "image/webp"}
      _ -> {:error, :invalid_content}
    end
  end
end

For more formats, the file_type package sniffs many types: FileType.from_path(path) returns {:ok, {"png", "image/png"}} or {:error, reason}. Still map the detected MIME type through your own allowlist. Broadcasts ({:created, image} etc.) follow the phoenix-pubsub-patterns skill.

LiveView

defmodule MyAppWeb.ImageLive.Index do
  use MyAppWeb, :live_view

  alias MyApp.Media

  @impl true
  def mount(_params, _session, socket) do
    {:ok,
     socket
     |> assign(:form, to_form(%{"title" => ""}, as: :image))
     |> stream(:images, Media.list_images(socket.assigns.current_scope))
     |> allow_upload(:images,
       accept: ~w(.jpg .jpeg .png .webp),
       max_entries: 5,
       max_file_size: 10_000_000,
       # Runs on client metadata, before any bytes arrive: early feedback only.
       # The magic-byte check in the context is the real gate.
       validator: &validate_entry/1
     )}
  end

  @impl true
  def handle_event("validate", %{"image" => params}, socket) do
    {:noreply, assign(socket, :form, to_form(params, as: :image))}
  end

  def handle_event("save", %{"image" => params}, socket) do
    scope = socket.assigns.current_scope

    # The temp file is deleted once the callback returns, so store and insert here,
    # but always return {:ok, result} and deal with failures below.
    results =
      consume_uploaded_entries(socket, :images, fn %{path: path}, entry ->
        attrs = Map.put(params, "original_name", entry.client_name)
        {:ok, Media.create_image(scope, path, attrs)}
      end)

    {saved, failed} = Enum.split_with(results, &match?({:ok, _}, &1))

    socket =
      Enum.reduce(saved, socket, fn {:ok, image}, acc ->
        stream_insert(acc, :images, image, at: 0)
      end)

    socket =
      if failed == [],
        do: socket,
        else: put_flash(socket, :error, "#{length(failed)} file(s) were not valid images")

    {:noreply, assign(socket, :form, to_form(%{"title" => ""}, as: :image))}
  end

  def handle_event("cancel-upload", %{"ref" => ref}, socket) do
    {:noreply, cancel_upload(socket, :images, ref)}
  end

  defp validate_entry(%{client_type: type}) do
    if Media.allowed_type?(type), do: :ok, else: {:error, :unsupported_type}
  end

  defp error_to_string(:too_large), do: "File is too large (max 10 MB)"
  defp error_to_string(:not_accepted), do: "Only JPEG, PNG and WebP images are accepted"
  defp error_to_string(:unsupported_type), do: "Only JPEG, PNG and WebP images are accepted"
  defp error_to_string(:too_many_files), do: "Too many files (max 5)"
  defp error_to_string(:external_client_failure), do: "Upload failed, please try again"
  defp error_to_string({:external_metadata_failure, _meta}), do: "Could not prepare the upload"
  defp error_to_string({:writer_failure, _reason}), do: "Could not store the file"
  defp error_to_string(_other), do: "Upload failed"
end

Template

render/1 (or the colocated .html.heex), wrapped in <Layouts.app flash={@flash} current_scope={@current_scope}> like the generators:

<.form for={@form} id="upload-form" phx-change="validate" phx-submit="save">
  <.input field={@form[:title]} label="Title" />

  <div phx-drop-target={@uploads.images.ref} class="border border-dashed p-4">
    <label for={@uploads.images.ref} class="label">Images (or drop them here)</label>
    <.live_file_input upload={@uploads.images} />
  </div>

  <p :for={err <- upload_errors(@uploads.images)} class="text-error">{error_to_string(err)}</p>

  <div :for={entry <- @uploads.images.entries} id={"entry-#{entry.ref}"}>
    <.live_img_preview entry={entry} width="120" />
    <progress value={entry.progress} max="100">{entry.progress}%</progress>
    <button type="button" phx-click="cancel-upload" phx-value-ref={entry.ref} aria-label="cancel">
      &times;
    </button>
    <p :for={err <- upload_errors(@uploads.images, entry)} class="text-error">
      {error_to_string(err)}
    </p>
  </div>

  <.button phx-disable-with="Uploading...">Upload</.button>
</.form>

<div id="images" phx-update="stream">
  <img
    :for={{id, image} <- @streams.images}
    id={id}
    src={MyApp.Media.image_url(image)}
    alt={image.title}
  />
</div>

phx-drop-target gets the phx-drop-target-active class while a file is dragged over it. live_file_input renders id={@uploads.images.ref}, which is what the <label for> points at.


Storing and Serving Local Files

Configure the directory per environment and serve it with a dedicated Plug.Static. An MFA from: is resolved on each request, so the runtime config applies in releases:

# config/dev.exs (add priv/uploads to .gitignore)
config :my_app, :uploads_dir, Path.expand("../priv/uploads", __DIR__)

# config/test.exs
config :my_app, :uploads_dir, Path.expand("../tmp/test_uploads", __DIR__)

# config/runtime.exs, inside `if config_env() == :prod do`: a mounted volume
config :my_app, :uploads_dir, System.fetch_env!("UPLOADS_DIR")
# lib/my_app_web/endpoint.ex, next to the generated Plug.Static
plug Plug.Static,
  at: "/uploads",
  from: {MyApp.Media, :uploads_dir, []},
  gzip: false,
  headers: %{
    "x-content-type-options" => "nosniff",
    "content-security-policy" => "default-src 'none'"
  }

Plug.Static sets the content type from the extension, which is safe only because the extension came from the sniffed type. Everything under /uploads is public: there is no auth before the router. Files that need authorization go through a controller (below).

Writing into priv/static/uploads and adding "uploads" to static_paths/0 works in dev only: the next release deploy wipes it.

Private files: scoped download controller

defmodule MyAppWeb.DocumentController do
  use MyAppWeb, :controller

  alias MyApp.Media

  # Route lives in the scope piped through :require_authenticated_user.
  def show(conn, %{"id" => id}) do
    # Scoped lookup: another user's id raises Ecto.NoResultsError (404).
    document = Media.get_document!(conn.assigns.current_scope, id)

    conn
    |> put_resp_header("x-content-type-options", "nosniff")
    |> send_download({:file, Media.document_path(document)},
      # Display name only; send_download encodes it into the header.
      filename: document.original_name,
      # Stored from the allowlist at upload time, not the client's type.
      content_type: document.content_type,
      disposition: :attachment
    )
  end
end

Media.document_path/1 is Path.join(private_dir(), document.filename), where filename is the server-generated UUID name. Keep private files outside any Plug.Static directory.


External Uploads (S3 and compatible)

The browser uploads straight to storage; the server only signs. Pick the key and the extension on the server:

# In mount: allow_upload(:images, accept: ..., validator: &validate_entry/1,
#                        external: &presign_upload/2)

defp presign_upload(entry, socket) do
  # With manual uploads, :external can be called for entries the validator
  # rejected, so check the allowlist again.
  with {:ok, ext} <- Media.extension_for(entry.client_type),
       key = "images/#{entry.uuid}#{ext}",
       {:ok, url} <- Media.presigned_put_url(key, entry.client_type) do
    {:ok, %{uploader: "S3", key: key, url: url, content_type: entry.client_type}, socket}
  else
    _ -> {:error, %{reason: "unsupported type"}, socket}
  end
end

# In "save", the callback receives the meta map returned above.
consume_uploaded_entries(socket, :images, fn %{key: key}, entry ->
  {:ok, Media.create_image_from_key(scope, key, entry, params)}
end)

Media.presigned_put_url/2 wraps your S3 client (for example ex_aws_s3's presigned URL function). Sign the content-type into the URL so storage rejects a different header, configure CORS on the bucket for your origin, and serve user content from a separate domain. The server never sees the bytes, so there is no magic-byte check unless you fetch and verify the object afterwards (for example in an Oban job).

Register the uploader on the client. Without this, LiveView logs "no uploader configured for S3" and nothing uploads:

// assets/js/app.js
const Uploaders = {}

Uploaders.S3 = function (entries, onViewError) {
  entries.forEach(entry => {
    const xhr = new XMLHttpRequest()
    onViewError(() => xhr.abort())
    xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? entry.progress(100) : entry.error())
    xhr.onerror = () => entry.error()
    xhr.upload.addEventListener("progress", event => {
      if (event.lengthComputable) {
        const percent = Math.round((event.loaded / event.total) * 100)
        if (percent < 100) entry.progress(percent)
      }
    })
    xhr.open("PUT", entry.meta.url, true)
    xhr.setRequestHeader("content-type", entry.meta.content_type)
    xhr.send(entry.file)
  })
}

const liveSocket = new LiveSocket("/live", Socket, {
  longPollFallbackMs: 2500,
  params: {_csrf_token: csrfToken},
  hooks: {...colocatedHooks},
  uploaders: Uploaders
})

entry.error() surfaces as :external_client_failure in upload_errors/2.


Custom Writers

writer: streams chunks somewhere other than a temp file (for example straight to another service). It takes a 3-arity function returning {module, opts}, where the module implements Phoenix.LiveView.UploadWriter (init/1, meta/1, write_chunk/2, close/2). Whatever meta/1 returns is what consume_uploaded_entries/3 receives instead of %{path: path}. Writers run in the upload channel process: blocking work blocks the upload, and an error from write_chunk/2 cancels the entry with {:writer_failure, reason}.

allow_upload(socket, :video,
  accept: ~w(.mp4),
  max_file_size: 500_000_000,
  writer: fn _name, entry, _socket -> {MyApp.StreamingWriter, upload_id: entry.uuid} end
)

Auto Upload

auto_upload: true starts uploading on file selection. Consume each entry from a progress: callback once it is done; consuming in a submit handler raises ArgumentError while any entry is still in progress.

# allow_upload(:avatar, accept: ~w(.jpg .jpeg .png), auto_upload: true,
#              progress: &handle_progress/3)

defp handle_progress(:avatar, entry, socket) do
  if entry.done? do
    scope = socket.assigns.current_scope

    result =
      consume_uploaded_entry(socket, entry, fn %{path: path} ->
        {:ok, MyApp.Accounts.update_avatar(scope, path)}
      end)

    case result do
      {:ok, _user} -> {:noreply, put_flash(socket, :info, "Avatar updated")}
      {:error, _reason} -> {:noreply, put_flash(socket, :error, "Not a valid image")}
    end
  else
    {:noreply, socket}
  end
end

Testing Uploads

setup :register_and_log_in_user

@png <<0x89, "PNG", 0x0D, 0x0A, 0x1A, 0x0A>> <> :binary.copy(<<0>>, 64)

test "uploads an image", %{conn: conn} do
  {:ok, lv, _html} = live(conn, ~p"/images")

  upload = file_input(lv, "#upload-form", :images, [%{name: "cat.png", content: @png, type: "image/png"}])
  assert render_upload(upload, "cat.png") =~ "100%"

  lv |> form("#upload-form", image: %{title: "Cat"}) |> render_submit()

  assert has_element?(lv, "#images img[alt='Cat']")
end

test "rejects a type that isn't accepted", %{conn: conn} do
  {:ok, lv, _html} = live(conn, ~p"/images")

  pdf = file_input(lv, "#upload-form", :images, [%{name: "a.pdf", content: "%PDF-1.7", type: "application/pdf"}])

  assert {:error, [[_ref, :not_accepted]]} = render_upload(pdf, "a.pdf")
end

test "rejects HTML that claims to be a PNG", %{conn: conn} do
  {:ok, lv, _html} = live(conn, ~p"/images")

  fake = file_input(lv, "#upload-form", :images, [%{name: "x.html", content: "<script>", type: "image/png"}])
  render_upload(fake, "x.html")

  assert lv |> form("#upload-form", image: %{title: "x"}) |> render_submit() =~ "not valid images"
end

file_input/4 only builds the upload; render_upload/3 is what sends it to the server, so assert on its result for validation errors. See the testing-essentials skill before writing any _test.exs file.


Troubleshooting

  • /uploads/... returns 404: the file isn't under MyApp.Media.uploads_dir(), or the Plug.Static at: "/uploads" plug is missing or placed after the router.
  • Uploads vanish after a deploy: they were written into priv/static (Rule 3). mix phx.digest doesn't help; it only fingerprints files that existed at build time.
  • Submit button doesn't render: it is inside an actions slot; <.form> only declares inner_block, so the slot is dropped with just a compile warning.
  • no uploader configured for S3 in the browser console: the uploaders: option is missing on LiveSocket.

Security Essentials

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Never use String.to_atom/1 on user input — atoms are never garbage collected; String.to_existing_atom/1 raises on unknown input (a 500). Map known strings with a case
  2. Never build SQL or identifiers from user input — fragment already rejects interpolated strings at compile time; the real holes are Repo.query/SQL.query with string interpolation and user-chosen columns (field(p, ^name), identifier(^name), order_by: ^...). Use $1 parameters and allowlist columns with a case
  3. Never pass user input to redirect(external: ...) — check the host against an allowlist first. redirect(to: ...) already raises on anything but a local path, so keep return paths server-side (session) like phx.gen.auth
  4. Avoid raw/1 — HEEx escapes {@x}; if HTML is required, sanitize with HtmlSanitizeEx first
  5. Keep secrets out of logs — redact: true on sensitive schema fields, extend :filter_parameters, and never pass tokens or credentials as Logger metadata or message text
  6. Compare secrets with Plug.Crypto.secure_compare/2 — never == or a pattern match
  7. Never :erlang.binary_to_term/1 untrusted bytes — it can build functions and atoms; use JSON, or Plug.Crypto.non_executable_binary_to_term(bin, [:safe])
  8. Give every signed token a purpose and an explicit max_age — Phoenix.Token.verify(endpoint, "purpose", token, max_age: ...); Phoenix.Token can't be revoked, so use database tokens (phx.gen.auth UserToken) for login sessions and API keys
  9. Validate outbound URLs (SSRF) — allowlist scheme and host before Req.get(url), and disable redirects
  10. Production transport and headers — keep the generated force_ssl (HSTS), and replace the default CSP, which only sets base-uri and frame-ancestors
  11. Run audits after dependency changes — mix hex.audit, mix deps.audit, mix sobelow

Atom Table Exhaustion

The atom table has a fixed limit (default 1,048,576) and is never garbage collected. Filling it crashes the whole VM.

role = String.to_atom(params["role"])          # unbounded atom creation
status = String.to_existing_atom(params["status"])  # ArgumentError (500) on unknown input
def parse_role("admin"), do: {:ok, :admin}
def parse_role("member"), do: {:ok, :member}
def parse_role(_), do: {:error, :invalid_role}

For schema fields, Ecto.Enum does this mapping for you when you cast.


SQL Injection

The query DSL parameterizes ^values, and fragment("lower(#{x})") is a compile error ("to prevent SQL injection attacks, fragment(...) does not allow strings to be interpolated"). The risks that remain:

# Raw SQL built with interpolation — injection
Repo.query("SELECT * FROM users WHERE email = '#{email}'")

# User picks the column: ?sort=hashed_password orders (and leaks) by the password hash
order_by(query, [u], asc: field(u, ^String.to_existing_atom(params["sort"])))

# identifier/1 is quoted, but the user still chooses which column or table is read
fragment("SELECT ? FROM users", identifier(^params["column"]))
# Parameters for raw SQL
Repo.query("SELECT * FROM users WHERE email = $1", [email])

# Allowlist user-chosen columns
defp sort_field("name"), do: :name
defp sort_field("inserted_at"), do: :inserted_at
defp sort_field(_), do: :inserted_at

def list_users(params) do
  from(u in User, order_by: [asc: field(u, ^sort_field(params["sort"])), asc: u.id])
  |> Repo.all()
end

splice(^list) sends each element as a parameter and is safe. constant(^value) inlines the value into the SQL (escaped), so each distinct value creates a new prepared query: don't feed it user input.


Open Redirects

redirect(conn, to: path) raises ArgumentError unless path starts with a single / and contains no \, tab or newline. So to: params["return_to"] is a crash, not an open redirect. The risk is external:, in controllers and in LiveView (redirect(socket, external: url)).

def callback(conn, %{"next" => next}) do
  redirect(conn, external: next)   # https://evil.example/login looks like it came from you
end
@allowed_hosts ["docs.example.com", "billing.example.com"]

def callback(conn, %{"next" => next}) do
  case URI.new(next) do
    {:ok, %URI{scheme: "https", host: host}} when host in @allowed_hosts ->
      redirect(conn, external: next)

    _ ->
      redirect(conn, to: ~p"/")
  end
end

For "return to where you were", copy phx.gen.auth: maybe_store_return_to/1 saves current_path(conn) in the session on GET requests and log_in_user/3 redirects to it with to:. The path never comes from a query param.


Cross-Site Scripting (XSS)

HEEx escapes every {@value} in text and attributes. raw/1 turns that off.

<div>{raw(@user_bio)}</div>
<a href={@user_url}>website</a>
<div>{@user_bio}</div>
<div>{raw(HtmlSanitizeEx.basic_html(@user_bio))}</div>
<p class="whitespace-pre-line">{@comment_body}</p>
  • Phoenix.HTML.Format was removed in phoenix_html 4. To keep line breaks in plain text, use CSS (whitespace-pre-line) rather than generating <br> tags.
  • Escaping doesn't make a URL safe: href={@user_url} with javascript:alert(1) still runs. Validate that the scheme is http/https before storing user URLs.
  • Uploaded files are another XSS route: see the phoenix-uploads skill. Never derive the stored extension or the served content type from the client.

Content Security Policy

The :browser pipeline's put_secure_browser_headers sets only content-security-policy: base-uri 'self'; frame-ancestors 'self';. That's clickjacking protection, not XSS protection. Pass a real policy:

# router.ex
@csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; " <>
       "img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'self'; " <>
       "base-uri 'self'; form-action 'self'; object-src 'none'"

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_live_flash
  plug :put_root_layout, html: {MyAppWeb.Layouts, :root}
  plug :protect_from_forgery
  plug :put_secure_browser_headers, %{"content-security-policy" => @csp}
  plug :fetch_current_scope_for_user
end

The Phoenix 1.8 root layout includes an inline theme <script>, which script-src 'self' blocks. Move it to its own static file loaded without defer, or add a per-request nonce. connect-src 'self' covers the LiveView websocket on the same host.


Sensitive Data in Logs

Phoenix replaces any request parameter whose name contains "password" with [FILTERED]. Extend that list:

# config/config.exs
config :phoenix, :filter_parameters, ["password", "token", "secret", "api_key"]

Mark sensitive schema fields redact: true, so inspect/1 (crash reports, Logger.error("...#{inspect(user)}")) prints **redacted**. phx.gen.auth already does this for password and hashed_password.

schema "integrations" do
  field :api_key, :string, redact: true
  field :webhook_secret, :string, redact: true
  timestamps(type: :utc_datetime)
end
Logger.info("API call", token: api_token, response: resp)
Logger.error("Auth failed for #{email} with #{password}")
require Logger

Logger.info("API call", endpoint: url, status: resp.status)
Logger.warning("Auth failed", user_id: user_id, reason: :invalid_credentials)

Plug.RequestId (in every generated endpoint) already sets request_id Logger metadata; don't overwrite it.


Timing Attacks and Tokens

def valid_signature?(given, expected), do: given == expected
def valid_signature?(given, expected), do: Plug.Crypto.secure_compare(given, expected)

Tokens you look up by a hash (the UserToken pattern) don't need this; the database comparison is on a hash the attacker can't steer.

Signed tokens (Phoenix.Token) default to a 1-day max_age. Always say what you mean:

token = Phoenix.Token.sign(MyAppWeb.Endpoint, "email-confirm", user.id)

case Phoenix.Token.verify(MyAppWeb.Endpoint, "email-confirm", token, max_age: 3600) do
  {:ok, user_id} -> {:ok, user_id}
  {:error, :expired} -> {:error, :expired}
  {:error, _invalid} -> {:error, :invalid}
end

Use a different namespace for each purpose. They're signed, not encrypted: the payload is readable (Phoenix.Token.encrypt/4 hides it). They can't be revoked before max_age, so they're wrong for "log out everywhere" or API keys. Use database tokens for those.


Unsafe Deserialization

:erlang.binary_to_term/1 on attacker-controlled bytes can create atoms (exhausting the table) and anonymous functions that a later call may execute.

state = :erlang.binary_to_term(Base.decode64!(params["state"]))
# Prefer JSON for anything that crosses a trust boundary
{:ok, state} = JSON.decode(params["state"])

# If it must be ETF: no new atoms, no executable terms
state = Plug.Crypto.non_executable_binary_to_term(bin, [:safe])

[:safe] alone still decodes local funs; non_executable_binary_to_term/2 rejects them. If the data round-trips through the client, sign it too (Phoenix.Token).


SSRF (Outbound Requests to User URLs)

A user-supplied URL (webhook, avatar URL, link preview) lets an attacker make your server call http://169.254.169.254/ (cloud metadata), localhost admin ports, or internal services.

@allowed_hosts ["api.partner.example"]

def fetch_partner_resource(url) do
  case URI.new(url) do
    {:ok, %URI{scheme: "https", host: host}} when host in @allowed_hosts ->
      # A redirect is a new, unchecked URL
      Req.get(url, redirect: false, retry: false)

    _ ->
      {:error, :url_not_allowed}
  end
end

If you must accept arbitrary hosts (webhooks), resolve the hostname and reject loopback, private (10/8, 172.16/12, 192.168/16), link-local (169.254/16) and IPv6 equivalents. Then connect to the IP you checked, because a second DNS lookup can return a different address (DNS rebinding). Run such fetches from a background job with a short timeout.

Req strips only authorization on cross-host redirects; custom API-key headers are forwarded. See the http-clients-req skill.


File Paths

Never build a filesystem path from client input: entry.client_name, params["file"], or any name stored from the client.

path = Path.join("priv/uploads", params["name"])   # "../../config/runtime.exs"
send_file(conn, 200, path)
# Store under a server-chosen name; look the record up through a scoped context
document = Media.get_document!(scope, id)
send_download(conn, {:file, Media.document_path(document)}, filename: document.original_name)

# If a relative path must come from input, Path.safe_relative/2 rejects ../ escapes
{:ok, rel} = Path.safe_relative(params["path"], Media.uploads_dir())

Path.basename/1 isn't a guard: Path.basename("..") is "..". See the phoenix-uploads skill for upload naming and content types.


Session Cookies, HTTPS and HSTS

  • HTTPS: Phoenix 1.8's config/prod.exs sets force_ssl: [rewrite_on: [:x_forwarded_proto], ...]. That redirects HTTP to HTTPS and sends HSTS (1 year by default). force_ssl is compile-time config: keep it in prod.exs, not runtime.exs. rewrite_on is required behind a TLS-terminating proxy; without it every request looks like HTTP and you get a redirect loop.
  • Session cookie: the generated @session_options are signed (signing_salt), http_only (the default) and same_site: "Lax". secure is added automatically when the request is HTTPS, which again depends on rewrite_on behind a proxy. Set secure: true explicitly if unsure. The cookie is signed, not encrypted: the user can read it. Add encryption_salt: if you store anything they shouldn't see.
  • WebSockets: keep check_origin enabled (the default) in production. See the phoenix-channels-essentials skill.

CSRF Protection

protect_from_forgery in the :browser pipeline checks a token on every non-GET request. <.form> and <.link method="delete"> include it for you. A hand-written <form> needs it explicitly:

<form action={~p"/export"} method="post">
  <input type="hidden" name="_csrf_token" value={get_csrf_token()} />
  <button type="submit">Export</button>
</form>

The :api pipeline has no CSRF check because it uses Authorization headers, not cookies. If an API endpoint reads the session cookie, it needs CSRF protection again.


Dependency and Code Auditing

# mix.exs
defp deps do
  [
    # ...
    {:mix_audit, "~> 2.1", only: [:dev, :test], runtime: false},
    {:sobelow, "~> 0.14", only: [:dev, :test], runtime: false}
  ]
end

defp aliases do
  [
    # ...
    "security.check": ["hex.audit", "deps.audit", "sobelow --exit"]
  ]
end
mix hex.audit              # retired packages (checksums are already verified via mix.lock)
mix deps.audit             # known CVEs in dependencies (mix_audit)
mix sobelow --save-config  # once: writes .sobelow-conf (commit it); later runs pick it up automatically
mix sobelow --exit         # non-zero exit on findings (low confidence and up), for CI

Sobelow flags Config.CSP until the :browser pipeline passes a "content-security-policy" header (see above). Silence a reviewed finding with a # sobelow_skip ["Module"] comment, not by dropping the check.


See the phoenix-authorization-patterns skill for access control. See the phoenix-json-api skill for API tokens and rate limiting. See the telemetry-essentials skill for the logging rules.

Telemetry Essentials

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026

RULES — Follow these with no exceptions

  1. Put values you'll filter on in Logger metadata; a human-readable message may interpolate — Logger.info("Order #{order.id} created", order_id: order.id); require Logger first, and list the metadata keys in the formatter config or they're dropped
  2. Configure log output with config :logger, :default_formatter (or :default_handler for a JSON formatter) — config :logger, :console is ignored when :default_formatter is set, which Phoenix 1.8's config.exs does
  3. Don't overwrite request_id — Plug.RequestId (in every generated endpoint) already sets it as Logger metadata; it is not in conn.assigns
  4. Attach handlers once at boot, with &__MODULE__.handle_event/4 and a catch-all clause — a handler that raises is detached permanently and silently; a local capture (&handle_event/4) makes telemetry warn about a performance penalty
  5. Use the events Ecto, Phoenix and Oban already emit — don't wrap queries manually; of Ecto's query measurements only total_time is always present, so read the others with Map.get/2
  6. Metric tags must have low cardinality — route, status, queue, source yes; user_id, request_id, email never. Per-user ids belong in log metadata and traces
  7. If the project has its own telemetry wrapper or event catalog, use it instead of calling :telemetry.execute/3 directly
  8. Logger metadata is per process — Task, GenServer and LiveView processes don't inherit it; pass it on explicitly
  9. LiveDashboard stays inside the generated dev_routes block, or behind admin auth — never in a scope with only :browser
  10. Never log at :debug in production — it includes query parameters (see the deployment-gotchas skill)

Logging

Metadata is what log tools index and filter on. The message is for humans and may interpolate.

# Nothing to filter on, and inspect(user) dumps the whole struct
Logger.info("User #{inspect(user)} created order")
require Logger

Logger.info("Order #{order.id} created", order_id: order.id, user_id: order.user_id)
Logger.error("Payment failed: #{inspect(reason)}", order_id: order.id, reason: inspect(reason))

Metadata keys not listed in the formatter config are silently dropped:

# config/config.exs — Phoenix 1.8 generates this block; extend the list
config :logger, :default_formatter,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id, :user_id, :order_id]

JSON logs in production

logger_json 7 plugs into Elixir's default handler:

# mix.exs
{:logger_json, "~> 7.0"}

# config/runtime.exs
if config_env() == :prod do
  config :logger, :default_handler,
    formatter: LoggerJSON.Formatters.Basic.new(metadata: [:request_id, :user_id, :order_id])
end

Basic.new/1 is only available in runtime.exs (deps are loaded by then). In config.exs/prod.exs use the tuple form {LoggerJSON.Formatters.Basic, metadata: [...]}. Formatters for Datadog, Google Cloud and Elastic exist alongside Basic.

# Ignored: :console is copied to :default_formatter only when :default_formatter
# is unset, and Phoenix 1.8's config.exs sets it
config :logger, :console, format: "$message\n", metadata: [:request_id]

Per-request and per-user metadata

request_id is already set by Plug.RequestId. Add the user once the scope is known, in a router plug and in a LiveView on_mount hook. A LiveView runs in its own process, so plug metadata doesn't reach it.

# router.ex — after :fetch_current_scope_for_user in the :browser pipeline
plug :put_user_log_metadata

defp put_user_log_metadata(conn, _opts) do
  with %{user: %{id: user_id}} <- conn.assigns[:current_scope] do
    Logger.metadata(user_id: user_id)
  end

  conn
end
defmodule MyAppWeb.LogMetadata do
  def on_mount(:default, _params, _session, socket) do
    with %{user: %{id: user_id}} <- socket.assigns[:current_scope] do
      Logger.metadata(user_id: user_id)
    end

    {:cont, socket}
  end
end

# router.ex — after the hook that assigns current_scope
live_session :require_authenticated_user,
  on_mount: [{MyAppWeb.UserAuth, :require_authenticated}, MyAppWeb.LogMetadata] do
  # live routes
end

Logger.metadata/1 is a plain function, so it needs no require Logger (an unused require is a warning).

Spawned processes lose metadata

metadata = Logger.metadata()

Task.Supervisor.start_child(MyApp.TaskSupervisor, fn ->
  Logger.metadata(metadata)
  deliver_webhook(event)
end)

The same applies to Oban jobs: put the ids you need in the job args and set metadata in perform/1. OpenTelemetry carries trace context across processes, but only in code instrumented to propagate it.


:telemetry Basics

# name (list of atoms), measurements (map), metadata (map)
:telemetry.execute([:my_app, :orders, :created], %{count: 1, total_cents: 4999}, %{source: :web})

Attaching handlers

# lib/my_app/application.ex
@impl true
def start(_type, _args) do
  MyApp.TelemetryHandlers.attach()

  children = [
    MyAppWeb.Telemetry,
    MyApp.Repo,
    MyAppWeb.Endpoint
  ]

  Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
defmodule MyApp.TelemetryHandlers do
  require Logger

  @events [
    [:my_app, :orders, :created],
    [:my_app, :payments, :failed]
  ]

  def attach do
    :telemetry.attach_many("my-app-handlers", @events, &__MODULE__.handle_event/4, nil)
  end

  def handle_event([:my_app, :orders, :created], measurements, metadata, _config) do
    Logger.info("Order created", total_cents: measurements.total_cents, source: metadata.source)
  end

  def handle_event([:my_app, :payments, :failed], _measurements, metadata, _config) do
    Logger.error("Payment failed: #{inspect(metadata.reason)}", order_id: metadata.order_id)
  end

  # Catch-all: an event added to @events without a clause must not crash the handler,
  # since telemetry would then detach it for every event in the list
  def handle_event(_event, _measurements, _metadata, _config), do: :ok
end

Handlers run synchronously in the process that emitted the event. Keep them fast, and send slow work (HTTP calls, heavy aggregation) to another process. :telemetry.attach/4 with an existing handler id returns {:error, :already_exists}.

Spans

def process_order(order) do
  :telemetry.span([:my_app, :orders, :process], %{order_id: order.id}, fn ->
    result = do_process(order)
    {result, %{order_id: order.id, status: elem(result, 0)}}
  end)
end

# Emits [:my_app, :orders, :process, :start]     — %{system_time: ..., monotonic_time: ...}
#       [:my_app, :orders, :process, :stop]      — %{duration: ..., monotonic_time: ...}
#       [:my_app, :orders, :process, :exception] — if the function raises, throws or exits

Ecto Telemetry

Each repo emits [:my_app, :repo, :query] (the prefix comes from the repo's :telemetry_prefix). Measurements are in :native units: total_time is always present, while query_time, queue_time, decode_time and idle_time are omitted when unknown. Metadata includes :query, :source (may be nil), :repo, :result, and :params. The params can contain personal data, so don't log them.

defmodule MyApp.SlowQueryLogger do
  require Logger

  def attach do
    :telemetry.attach("slow-queries", [:my_app, :repo, :query], &__MODULE__.handle_event/4, %{
      threshold_ms: 100
    })
  end

  def handle_event(_event, measurements, metadata, %{threshold_ms: threshold}) do
    total_ms = System.convert_time_unit(measurements.total_time, :native, :millisecond)

    if total_ms > threshold do
      queue_ms = System.convert_time_unit(Map.get(measurements, :queue_time, 0), :native, :millisecond)

      Logger.warning("Slow query (#{total_ms}ms) on #{metadata.source || "unknown"}",
        duration_ms: total_ms,
        queue_ms: queue_ms,
        source: metadata.source,
        query: metadata.query
      )
    end
  end
end

A high queue_ms means the pool is too small or connections are held too long. A high query time means the query itself needs work. To act on a slow query (EXPLAIN, indexes, preloads), see the ecto-queries-performance skill.


Phoenix Events

# [:phoenix, :endpoint, :start | :stop]
# [:phoenix, :router_dispatch, :start | :stop | :exception]   — metadata has :route
# [:phoenix, :live_view, :mount | :handle_params | :handle_event, :start | :stop | :exception]
# [:phoenix, :live_component, :handle_event, :start | :stop | :exception]
# [:phoenix, :socket_connected], [:phoenix, :channel_joined], [:phoenix, :channel_handled_in]

Metrics (Telemetry.Metrics)

Phoenix generates MyAppWeb.Telemetry with a metrics/0 list. Add to it rather than writing a second module.

def metrics do
  [
    summary("phoenix.router_dispatch.stop.duration",
      tags: [:route],
      unit: {:native, :millisecond}
    ),

    # tag_values derives a low-cardinality tag from metadata
    counter("my_app.orders.process.stop.duration",
      tags: [:status],
      tag_values: fn metadata -> %{status: Map.get(metadata, :status, :unknown)} end
    ),

    # keep records only the events you care about
    summary("my_app.repo.query.total_time",
      tags: [:source],
      unit: {:native, :millisecond},
      keep: fn metadata -> metadata[:source] != "oban_jobs" end
    ),

    last_value("vm.memory.total", unit: {:byte, :kilobyte})
  ]
end

Each distinct tag combination is a separate time series. Tagging by user_id or request_id creates one series per user or request. That makes the reporter's memory grow without bound and the metrics bill with it.

Reporters are children that take metrics: MyAppWeb.Telemetry.metrics():

  • telemetry_metrics_prometheus: {TelemetryMetricsPrometheus, metrics: metrics()} serves /metrics on port 9568. It doesn't support summary; use distribution (histogram buckets) instead.
  • telemetry_metrics_statsd: {TelemetryMetricsStatsd, metrics: metrics()}, for Datadog and StatsD agents.

Tracing (OpenTelemetry)

For distributed traces, add opentelemetry and opentelemetry_exporter (configure the exporter for your backend), then call the instrumentation setups in Application.start/2 before the supervisor starts:

OpentelemetryBandit.setup()
OpentelemetryPhoenix.setup(adapter: :bandit)
OpentelemetryEcto.setup([:my_app, :repo])
OpentelemetryOban.setup()

These come from opentelemetry_bandit, opentelemetry_phoenix, opentelemetry_ecto and opentelemetry_oban. Per-user ids go on spans as attributes, never as metric tags. For outbound HTTP spans (OpentelemetryReq) and per-API Req metrics, see the http-clients-req skill.


LiveDashboard

Phoenix generates it inside the dev_routes block, which only compiles in dev. Keep it there:

# router.ex (generated)
if Application.compile_env(:my_app, :dev_routes) do
  import Phoenix.LiveDashboard.Router

  scope "/dev" do
    pipe_through :browser

    live_dashboard "/dashboard", metrics: MyAppWeb.Telemetry
    forward "/mailbox", Plug.Swoosh.MailboxPreview
  end
end

To use it in production, mount it behind authentication. Use your own admin plug, or Plug.BasicAuth over HTTPS:

import Phoenix.LiveDashboard.Router

pipeline :admin_basic_auth do
  plug :dashboard_auth
end

scope "/admin" do
  pipe_through [:browser, :admin_basic_auth]

  live_dashboard "/dashboard", metrics: MyAppWeb.Telemetry, ecto_repos: [MyApp.Repo]
end

defp dashboard_auth(conn, _opts) do
  Plug.BasicAuth.basic_auth(conn,
    username: System.fetch_env!("DASHBOARD_USER"),
    password: System.fetch_env!("DASHBOARD_PASSWORD")
  )
end

It exposes process state, ETS contents and request logs. Anyone who can reach it can read data from every user.


Testing Telemetry

:telemetry_test.attach_event_handlers/2 sends each matching event to the test process:

test "processing an order emits a stop event", %{scope: scope} do
  ref = :telemetry_test.attach_event_handlers(self(), [[:my_app, :orders, :process, :stop]])
  order = order_fixture(scope)

  Orders.process_order(order)

  assert_received {[:my_app, :orders, :process, :stop], ^ref, %{duration: _},
                   %{order_id: order_id, status: :ok}}

  assert order_id == order.id
end

Handlers are global. With async: true, events from other tests can arrive too, so match on metadata that identifies your test's data (order_id above).


See the deployment-gotchas skill for production log levels and configuration. See the security-essentials skill for what must never be logged. See the otp-essentials skill for process supervision.

Testing Essentials

Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14, Req 0.7 — October 2026

For longer worked examples (a full context + LiveView suite, uploads, Mox wiring, sandbox allowances, StreamData), read the testing reference when the patterns below aren't enough.

RULES — Follow these with no exceptions

  1. Follow the project's existing test setup patterns (e.g. shared setup helpers like setup :store_test_session) — don't inline DataCase/ConnCase boilerplate that the project already abstracts away
  2. Test both happy path AND error/invalid cases for every function
  3. Prefer async: true — it is safe under the Ecto SQL Sandbox, for DataCase and ConnCase/LiveView tests alike. Opt out only for real shared state: Application.put_env, named or app-supervised processes, Mox/Req.Test global mode. (Generators are inconsistent: phx.gen.auth's web tests are async, but its accounts_test.exs and the phx.gen.live / phx.gen.context tests aren't — add it.)
  4. Use the generated fixtures and scopes — user_fixture/1, user_scope_fixture/0, post_fixture(scope, attrs), and setup :register_and_log_in_user (puts conn, user and scope in the context). New fixtures go in test/support/fixtures/, never inline across tests
  5. Test authorization both ways — guests are redirected to ~p"/users/log-in", and a record created under one scope can't be read or changed through another
  6. Assert LiveView structure with has_element?/3, not html =~ on markup. When an event navigates, pipe into follow_redirect/2 and assert on the page you land on — the old view is gone
  7. Mock only at boundaries — Mox against a behaviour with setup :verify_on_exit!; HTTP through Req.Test stubs. Never mock your own contexts or Repo
  8. Never Process.sleep/1 — use assert_receive, render_async/2, start_supervised!/1
  9. Test the public context interface, not private helpers or internal state
  10. Use describe blocks to group tests by function or behavior

TDD Workflow

Write the failing test first, run it, confirm it fails for the right reason, then implement the minimum to pass.

mix test test/my_app/blog_test.exs:42   # one test by line
mix test --failed                       # re-run only last run's failures
mix test --stale                        # only tests affected by changed modules
mix test --warnings-as-errors           # fail on compile warnings in test files (CI)

Case Templates

DataCase (context and schema tests) has no conn. ConnCase (controllers, LiveViews) builds one and checks out the sandbox. Both call setup_sandbox/1, which starts a sandbox owner per test — that's why async: true is safe.

defmodule MyApp.BlogTest do
  use MyApp.DataCase, async: true

  alias MyApp.Blog
  import MyApp.AccountsFixtures, only: [user_scope_fixture: 0]
  import MyApp.BlogFixtures
end

defmodule MyAppWeb.PostLiveTest do
  use MyAppWeb.ConnCase, async: true

  import Phoenix.LiveViewTest
  import MyApp.BlogFixtures
end

Fixtures

Follow the shape phx.gen.context emits with scopes: the scope comes first, attrs merge over defaults, the record goes through the real context function.

defmodule MyApp.BlogFixtures do
  def post_fixture(scope, attrs \\ %{}) do
    attrs = Enum.into(attrs, %{title: "some title", body: "some body"})
    {:ok, post} = MyApp.Blog.create_post(scope, attrs)
    post
  end
end

phx.gen.auth (1.8) registration is email-only. user_fixture/1 already confirms the user via magic link; use unconfirmed_user_fixture/1 for the unconfirmed case and set_password/1 when a test needs a password. When you add a field to users, add it to valid_user_attributes/1 — don't write a new user fixture.

Fixtures for a custom scope entry (org_scope_fixture/0, its test_setup_helper) are in the phoenix-scopes-and-generators skill.


Context Test Skeleton

describe "posts" do
  test "list_posts/1 returns only the scope's posts" do
    scope = user_scope_fixture()
    other_scope = user_scope_fixture()
    post = post_fixture(scope)
    _other = post_fixture(other_scope)

    assert Blog.list_posts(scope) == [post]
  end

  test "get_post!/2 raises for another user's post" do
    post = post_fixture(user_scope_fixture())
    assert_raise Ecto.NoResultsError, fn -> Blog.get_post!(user_scope_fixture(), post.id) end
  end

  test "create_post/2 with valid attrs sets the owner from the scope" do
    scope = user_scope_fixture()
    assert {:ok, %Post{} = post} = Blog.create_post(scope, %{title: "Hello", body: "Hi"})
    assert post.user_id == scope.user.id
  end

  test "create_post/2 with invalid attrs returns an error changeset" do
    assert {:error, %Ecto.Changeset{} = changeset} = Blog.create_post(user_scope_fixture(), %{})
    assert %{title: ["can't be blank"]} = errors_on(changeset)
  end
end

LiveView Test Skeleton

Mirrors phx.gen.live's live_test.exs. render_change/1 returns HTML, so the apostrophe is escaped (can&#39;t). A submit that navigates must be followed; the flash is on the new page.

defmodule MyAppWeb.PostLiveTest do
  use MyAppWeb.ConnCase, async: true

  import Phoenix.LiveViewTest
  import MyApp.BlogFixtures

  setup :register_and_log_in_user

  defp create_post(%{scope: scope}), do: %{post: post_fixture(scope)}

  test "redirects guests to log in" do
    assert {:error, {:redirect, %{to: path}}} = live(build_conn(), ~p"/posts")
    assert path == ~p"/users/log-in"
  end

  describe "Index" do
    setup [:create_post]

    test "lists the user's posts", %{conn: conn, post: post} do
      {:ok, lv, _html} = live(conn, ~p"/posts")
      assert has_element?(lv, "#posts-#{post.id}", post.title)
    end

    test "deletes a post", %{conn: conn, post: post} do
      {:ok, lv, _html} = live(conn, ~p"/posts")
      lv |> element("#posts-#{post.id} a", "Delete") |> render_click()
      refute has_element?(lv, "#posts-#{post.id}")
    end
  end

  describe "Form" do
    test "validates, then saves and redirects", %{conn: conn} do
      {:ok, lv, _html} = live(conn, ~p"/posts/new")

      assert lv
             |> form("#post-form", post: %{title: nil})
             |> render_change() =~ "can&#39;t be blank"

      assert {:ok, index_lv, _html} =
               lv
               |> form("#post-form", post: %{title: "New Post", body: "Body"})
               |> render_submit()
               |> follow_redirect(conn, ~p"/posts")

      html = render(index_lv)
      assert html =~ "Post created successfully"
      assert html =~ "New Post"
    end
  end
end

<.input> errors render as <p class="... text-error"> in 1.8's core_components.ex, so a structural check is has_element?(lv, "#post-form p.text-error", "can't be blank") — has_element?/3 matches decoded text, so no &#39; there.

LiveViewTest helpers worth knowing

HelperUse
render_async(lv)Await assign_async/start_async/stream_async, then render. Default timeout is 100 ms — pass a larger one for slow work
assert_patch(lv, path)After a push_patch (same LiveView). Returns the path when called without one
assert_redirect(lv, path)After push_navigate or redirect from an event; returns the flash map
follow_redirect(result, conn)Mount the destination from a {:error, {:redirect, _}} result of live/2 or a render_* call
render_hook(lv, "event", params)Fire an event that a JS hook would push (no DOM element needed)
live_isolated(conn, MyLive, session: %{})Mount a LiveView without a route — good for components and uploads
open_browser(lv)Debug only: dumps current HTML to a browser. Never commit it
form(lv, sel, data)Validates data against the form's markup: unknown fields, disabled inputs and select values not in the options raise ArgumentError

render_submit/1 sends the form's values as currently rendered plus what you gave form/3 — not what an earlier render_change sent. Values survive only if the server re-rendered them into the inputs (<.input field={@form[:x]}> does; a <select> rendered without selected doesn't). Pass the full params to form/3 on the submit too.

LiveView 1.1+ parses test HTML with LazyHTML, not Floki — phx.new adds {:lazy_html, ">= 0.1.0", only: :test}. Keep Floki as a dependency only if your own tests call Floki directly; prefer has_element?/3 over hand-parsing.


Changeset Test Skeleton

describe "changeset/3" do
  test "requires title" do
    changeset = Post.changeset(%Post{}, %{}, user_scope_fixture())
    assert %{title: ["can't be blank"]} = errors_on(changeset)
  end
end

Mocks: Mox at Behaviour Boundaries

Mox needs three pieces: a behaviour the real module implements, a config switch, and the mock defined in test/test_helper.exs. Without setup :verify_on_exit!, a expect that is never called passes silently.

# lib/my_app/storage.ex — callers use MyApp.Storage.put/2, never the impl directly
defmodule MyApp.Storage do
  @callback put(key :: String.t(), data :: binary()) :: {:ok, String.t()} | {:error, term()}

  def put(key, data), do: impl().put(key, data)

  defp impl, do: Application.get_env(:my_app, :storage, MyApp.Storage.S3)
end

# config/test.exs:      config :my_app, :storage, MyApp.StorageMock
# test/test_helper.exs: Mox.defmock(MyApp.StorageMock, for: MyApp.Storage)

defmodule MyApp.AvatarsTest do
  use MyApp.DataCase, async: true

  import Mox

  setup :verify_on_exit!

  test "stores the avatar under the user's key" do
    scope = MyApp.AccountsFixtures.user_scope_fixture()

    expect(MyApp.StorageMock, :put, fn "avatars/" <> _, _data -> {:ok, "https://cdn.example/a.png"} end)

    assert {:ok, user} = MyApp.Avatars.update(scope, "png-bytes")
    assert user.avatar_url == "https://cdn.example/a.png"
  end
end

Mox expectations are per-process. Calls from Tasks and LiveViews started by the test are allowed automatically ($callers); for any other process use Mox.allow(MyApp.StorageMock, self(), pid). Full wiring in the testing reference.


HTTP: Req.Test Stubs

Req is Phoenix 1.8's default HTTP client. Route requests through a named Req.Test plug in test config; stubs are per-test and async-safe.

# lib/my_app/weather.ex (trimmed; the full client is in the http-clients-req skill)
defmodule MyApp.Weather do
  def current(city) do
    req_options = :my_app |> Application.get_env(__MODULE__, []) |> Keyword.get(:req_options, [])

    [base_url: "https://api.weather.example", url: "/v1/current", params: [city: city]]
    |> Keyword.merge(req_options)
    |> Req.request()
    |> case do
      {:ok, %Req.Response{status: 200, body: %{"celsius" => celsius}}} -> {:ok, celsius}
      {:ok, %Req.Response{status: status}} -> {:error, {:unexpected_response, status}}
      {:error, exception} -> {:error, exception}
    end
  end
end

# config/test.exs — retry: false or transport-error tests sleep through Req's backoff
# config :my_app, MyApp.Weather, req_options: [plug: {Req.Test, MyApp.Weather}, retry: false]

defmodule MyApp.WeatherTest do
  use ExUnit.Case, async: true

  test "parses the temperature" do
    Req.Test.stub(MyApp.Weather, fn conn -> Req.Test.json(conn, %{"celsius" => 21.5}) end)
    assert {:ok, 21.5} = MyApp.Weather.current("Lisbon")
  end

  test "surfaces transport errors" do
    Req.Test.stub(MyApp.Weather, &Req.Test.transport_error(&1, :timeout))
    assert {:error, %Req.TransportError{reason: :timeout}} = MyApp.Weather.current("Lisbon")
  end
end

Use Req.Test.expect/3 + setup {Req.Test, :verify_on_exit!} when the number of calls matters. Client design, retry policy, allowances for app-started processes and Finch pools are in the http-clients-req skill.


Processes, Logs, Files

test "counter starts at zero" do
  # Stopped after the test. Unnamed, so async tests (and an app-started
  # MyApp.Counter) don't collide; pass a unique name if the API needs one.
  pid = start_supervised!({MyApp.Counter, name: nil})
  assert MyApp.Counter.value(pid) == 0
end

@tag :capture_log                                       # hide expected error logs
test "logs and returns an error on bad input" do
  assert {:error, :invalid} = MyApp.Importer.run("garbage")
end

test "warns about the retry" do
  log = ExUnit.CaptureLog.capture_log(fn -> MyApp.Importer.run("retry-me") end)
  assert log =~ "retrying"
end

@tag :tmp_dir                                           # unique dir per test, in context
test "writes the export", %{tmp_dir: dir} do
  path = Path.join(dir, "out.csv")
  :ok = MyApp.Export.write(path)
  assert File.exists?(path)
end

Sandbox allowances. The SQL sandbox connection belongs to the test process. Tasks and LiveViews started from the test inherit it via $callers; a GenServer (even one from start_supervised!) or anything already running in the application tree does not, and fails with DBConnection.OwnershipError in async tests. Allow it explicitly:

pid = start_supervised!(MyApp.Indexer)
Ecto.Adapters.SQL.Sandbox.allow(MyApp.Repo, self(), pid)

Email and Jobs

phx.new configures Swoosh.Adapters.Test in config/test.exs. It sends {:email, email} to the delivering process and its $callers, so mail sent from a LiveView or Task under test reaches the test process.

import Swoosh.TestAssertions

test "sends the invite" do
  {:ok, _} = MyApp.Teams.invite(user_scope_fixture(), "new@example.com")
  assert_email_sent(to: "new@example.com", subject: "You're invited")
end

For Oban jobs (Oban.Testing, assert_enqueued, perform_job/2), see the oban-essentials skill.


Parameterized Tests (Elixir 1.18+)

Run a whole module once per parameter map; each map is merged into the test context. With async: true the parameter sets run concurrently.

defmodule MyApp.CacheTest do
  use ExUnit.Case,
    async: true,
    parameterize: [%{adapter: MyApp.Cache.ETS}, %{adapter: MyApp.Cache.Mnesia}]

  test "round-trips a value", %{adapter: adapter} do
    :ok = adapter.put(:k, 1)
    assert adapter.get(:k) == 1
  end
end

For property-based tests (use ExUnitProperties, check all), see the testing reference.


Timestamp Testing

Never hardcode dates — use relative timestamps so tests don't rot.

# Bad — breaks after 2026
assert post.published_at == ~U[2026-01-15 12:00:00Z]
# Good — within 5 seconds of now (abs: inserted_at is in the past, so the diff is negative)
assert abs(DateTime.diff(post.inserted_at, DateTime.utc_now(), :second)) < 5

# Good — relative dates for filtering/sorting
past = DateTime.add(DateTime.utc_now(:second), -7, :day)
future = DateTime.add(DateTime.utc_now(:second), 7, :day)
old_post = post_fixture(scope, published_at: past)
_future_post = post_fixture(scope, published_at: future)
assert Blog.list_published_posts(scope) == [old_post]

Sponsors

Details

Marketplace
j-morgan6/elixir-phoenix-guide
Category
Community