
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-guideRun it inside Claude Code after adding the marketplace with /plugin marketplace add j-morgan6/elixir-phoenix-guide.
Contents
Discovered from sourceSkills 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
- Run
mix compile --warnings-as-errorsfirst — the compiler reports unused private functions, variables, aliases and imports exactly; fix those before anything else - Then run
mix credo --strictwhen the project has Credo — its.credo.exsthresholds override the numbers in this skill - 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
- Keep branch complexity low — split functions the analyzer flags (above 15) or Credo flags (
CyclomaticComplexity, default max 9) into pattern-matched clauses or helpers - Take a baseline before a large refactor — run the analyzer before and after, and compare
- Address duplication before complexity — extracting shared code often removes branches too
- Share code through plain modules — callers
aliasorimportthe shared module; don't build__using__base modules just to share functions - Repeated HEEx markup becomes a function component — a manual guideline; no tool checks templates
Order of tools
mix compile --warnings-as-errors— unused code (the plugin no longer has its own unused-function check; the compiler is exact)mix credo --strict— the standard style and complexity checks.Refactor.CyclomaticComplexityis on by default (max 9);Design.DuplicatedCodeandRefactor.ABCSizeare opt-in in Credo's default configmix xref callers MyApp.Mod.fun/2andmix xref graph— who uses a function or module across the project- 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 testandmix compile --warnings-as-errorsagain 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
- Start from
mix phx.gen.release --docker— it generatesMyApp.Release,bin/migrate,bin/serverand a Dockerfile in the right build order; don't hand-write them - Environment values go in
runtime.exs; compile-time settings stay inconfig/prod.exs—force_ssland anything read withApplication.compile_envcan't be changed at boot - Run migrations with
bin/migratebefore 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) - Start the server with
bin/server(setsPHX_SERVER=true) and setPHX_HOST—runtime.exsenables the server only whenPHX_SERVERis set; a wrong host breaks generated URLs and the websocketcheck_origin - Build order is
deps.compile→compile→assets.deploy→release— colocated hooks are extracted duringmix compile, so assets built before compiling miss them - Never hardcode secrets — read them in
runtime.exsand fail at boot if missing - Split health checks: liveness never touches the database, readiness does — and neither returns error details (
inspect(reason)leaks hostnames) - Behind a load balancer: keep
force_sslwithrewrite_on: [:x_forwarded_proto], enable database SSL, keepcheck_origin - Use
config :logger, level: :infoin production —:debuglogs query parameters, which contain user data
1. Generate the Release Files
mix phx.gen.release --docker
It creates:
lib/my_app/release.ex—migrate/0androllback/2, runnable without Mixrel/overlays/bin/migrate— runs./my_app eval MyApp.Release.migraterel/overlays/bin/server— runsPHX_SERVER=true exec ./my_app startDockerfileand.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:
| Change | Safe sequence |
|---|---|
| Add a column | Add it as nullable or with a default → deploy the code that writes it → backfill → add NOT NULL later |
| Rename a column | Add the new column → write both → backfill → read the new one → drop the old one in a later deploy |
| Drop a column | Stop reading it (remove it from the schema) → deploy → drop it in the next deploy |
| Add an index on a big table | create 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 setsPHX_SERVER=true.bin/my_app startalone boots the app without the HTTP listener. Keep the conditional rather than an unconditionalserver: true, so you can still boot a node without the listener (a worker-only node, or abin/my_app start_iexmaintenance console). - Set
PHX_HOST. The fallback"example.com"produces wrong links and makescheck_originreject every websocket connection. ECTO_IPV6=truemakes the Repo connect over IPv6 (socket_options: [:inet6]). Fly.io's private network, for example, is IPv6-only.DNS_CLUSTER_QUERYfeeds 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.exshasforce_ssl: [rewrite_on: [:x_forwarded_proto], exclude: [hosts: ["localhost", "127.0.0.1"]]].rewrite_onmakes the app trust the proxy'sx-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.exsleaves# ssl: truecommented out. With Postgrex 0.21+,ssl: trueverifies the server certificate against the OS CA store (:public_key.cacerts_get()). If you pass a keyword list instead (ssl: [...]), addcacerts: :public_key.cacerts_get()(orcacertfile:for a provider's private CA) yourself: the list form doesn't add CA certificates. - WebSocket origin: keep
check_originon; it compares theOriginheader withurl: [host: ...](soPHX_HOSTmust be right), and several domains are listed explicitly. See thephoenix-channels-essentialsskill.
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, sobin/migratecovers 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.exsand switch it off per node inruntime.exswithqueues: 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]fromconfig.exssurvives the merge. For the same reason, aqueues: [...]list inruntime.exsis merged into theconfig.exslist, 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
- Create separate named changesets per operation —
email_changeset,password_changeset,profile_changeset; never onechangeset/2that casts everything - Never
castforeign keys or privileged fields (:user_id,:org_id,:role,:confirmed_at,:deleted_at) — set them withput_change/changefrom trusted code after a scope-checked lookup; for owned records use the Phoenix 1.8changeset(struct, attrs, scope)shape - Compose changesets with pipes — each validation step is a small private function reused across changesets
- Pair
unsafe_validate_uniquewithunique_constraint— the first gives live form feedback, the second catches the race; both are case-sensitive unless the column iscitext - Use
update_change/3for normalisation (trim, downcase, slug) — in the changeset, never in the controller or LiveView; call it aftervalidate_required - Accept
opts \\ []to skip expensive steps during live validation — phx.gen.auth'svalidate_unique: false(no DB query per keystroke) andhash_password: false(no Bcrypt per keystroke) - Passwords:
min: 12, max: 72, plusmax: 72, count: :bytesbefore hashing — Bcrypt only reads the first 72 bytes, and multibyte characters pass a character-count check - Validate in the changeset, not in context functions — contexts stay thin wrappers around
Repocalls
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: falsekeeps:passwordin the changes (so the form re-renders it) and skips the deliberately slow Bcrypt hash.validate_unique: falseskipsunsafe_validate_unique's database query;unique_constraintstill protects the insert.- Don't add options that skip validations to make tests faster — use the generated fixtures (see the
testing-essentialsskill).
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
- 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 - Never
castforeign keys or privileged fields (:user_id,:folder_id,:role,:org_id,:confirmed_at,:deleted_at) — set them withput_change/Ecto.build_assocafter a scope-checked lookup; use the 1.8changeset(struct, attrs, scope)shape - Always use changesets for inserts and updates — never pass raw maps to Repo
- Use
Repo.transact/2withwithfor multi-step writes;Repo.transaction/2is soft-deprecated since Ecto 3.13. Reach forEcto.Multionly when the steps are dynamic (see theecto-nested-associationsskill) - Preload associations before accessing them — avoid N+1 queries
- Add database constraints AND changeset constraint functions —
unique_index+unique_constraint,references+foreign_key_constraint - Index every foreign key and every column you filter or sort on
- Use
timestamps(type: :utc_datetime)in schemas and migrations — matches Phoenix 1.8'stimestamp_type: :utc_datetime - Escape
%,_and\in user search terms before building alike/ilikepattern - Keep
change/0migrations reversible —remove/3with the type,modifywithfrom:,execute/2with an up and a down - Database access goes through contexts — never call
Repofrom 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}fromcreate_folder/2falls out ofwithand rolls back — noRepo.rollback/1or catch-allelseneeded.update_allskips changesets and autogenerated timestamps: setupdated_atyourself, and keep the scope filter in the query.- Use
Ecto.Multiwhen the number of steps depends on input (one step per cart item, etc.) — see theecto-nested-associationsskill.
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_targetmust match a unique index exactly; its columns are never rewritten (replace_changed: trueis 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: truethe returned struct holds the values you tried to insert (e.g. a freshinserted_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
- Index existing tables with
concurrently: trueplus both@disable_ddl_transaction trueand@disable_migration_lock true, one index per migration. With only the first, the migration hangs forever under the default migration lock. - Set
lock_timeoutin every transactional migration that alters a busy table:after_begin/0callingrepo().query!("SET LOCAL lock_timeout TO '5s'"). Neverexecute/1there, because it breaks rollback ofchange/0. - 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. NOT NULLtakes three migrations:CHECK (col IS NOT NULL)withvalidate: false, thenVALIDATE CONSTRAINT, thenSET NOT NULLthroughexecute/2. Don't usemodify ... null: falsefor this step: it also emitsALTER COLUMN TYPE, which rescans the table.- Add foreign keys and check constraints to populated tables with
validate: false, then validate them in a later migration. - 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. - 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. - 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. - Make every migration reversible (
execute/2,modify ... from:,remove/3with a type) or writeup/0/down/0. Keep migrations without a transaction to a single idempotent step, because they can fail half-applied. - Run migrations before the new code takes traffic (see the
deployment-gotchasskill), and read the generated SQL withmix ecto.migrate --log-migrations-sqlbefore 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) | no | briefly |
add :col, :type, default: "constant" (constant default, even with null: false) | no | briefly |
add :col, :uuid, default: fragment("gen_random_uuid()") | rewrite | for the whole rewrite |
modify :title, :text, from: :string (varchar → text) | no | briefly |
integer → bigint, or any other non-binary-compatible type | rewrite | for the whole rewrite |
SET NOT NULL | full scan, unless a validated CHECK (col IS NOT NULL) exists | for the scan |
create constraint(..., validate: false) / references(..., validate: false) | no | briefly |
VALIDATE CONSTRAINT | scan | no (SHARE UPDATE EXCLUSIVE) |
create index | scan | blocks writes for the build |
create index(..., concurrently: true) | scan | no |
rename, remove | no | briefly, 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):
| Attributes | Result |
|---|---|
| neither | ERROR 25001 CREATE INDEX CONCURRENTLY cannot run inside a transaction block |
only @disable_ddl_transaction | hangs 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 |
| both | works |
only @disable_ddl_transaction, plus repo migration_lock: :pg_advisory_lock | works, no warning |
@disable_migration_lock truelets 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, setconfig :my_app, MyApp.Repo, migration_lock: :pg_advisory_lockinstead. It's session-level, so it doesn't work behind PgBouncer in transaction pooling mode.concurrentlyis only for tables that already hold data. An index in the same migration ascreate tableneeds neither attribute.- A failed concurrent build leaves an
INVALIDindex behind. For example,create unique_index(..., concurrently: true)fails on duplicate rows. Re-running the migration then fails with42P07 relation "..." already exists. Find it withSELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid, runDROP 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/0runs right after the migration transaction opens, onupand ondown.SET LOCALlimits the setting to that transaction. A plainSETwould stay on the pooled connection.- Use
repo().query!and notexecute "SET ...".after_begin/0runs in the same direction aschange/0, so on rollback Ecto tries to reverse theexecute/1and raisescannot reverse migration command. after_begin/0doesn't run in@disable_ddl_transactionmigrations, and a plainrepo().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 withrepo().checkout/1. See the migrations safety reference.- To apply it to every migration, use the pattern from the
Ecto.Migrationdocs: aMyApp.Migrationmodule whose__using__/1doesuse Ecto.Migrationand definesafter_begin/0. Thenuse MyApp.Migrationin each migration. - Ecto runs migration DDL with no client timeout (
timeout: :infinity), but astatement_timeoutset on the database role still applies. If your role has one, scans likeVALIDATEand index builds can be cancelled. Override it in that migration withSET 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, orVALIDATEfails. - Steps 1 and 2 must be separate migrations. In one transaction, the
ACCESS EXCLUSIVElock fromADD CONSTRAINTis held for the whole validating scan. - Step 3 measured: about 0.3 ms with
executeagainst about 55 ms formodify :title, :string, null: false, from: {:string, null: true}on 2M rows. Themodifyform generatesALTER COLUMN "title" TYPE varchar(255), ALTER COLUMN "title" SET NOT NULL, and theTYPEclause makes PostgreSQL verify the table again. drop constraint/2can't be reversed inchange/0, so step 3 usesexecute/2for 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: :bigintworks. It emits a no-opALTER COLUMN TYPE bigintalong withADD CONSTRAINT ... NOT VALID. - The constraint name is
<table>_<column>_fkeyunless you passname:.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.
| Change | Steps (each one is its own deploy) |
|---|---|
| Rename a column | add the new column → write both → backfill → read the new one → stop writing the old one → drop it |
| Rename only in code | field :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 column | remove the field from the schema and deploy → drop the column in the next deploy |
| Rename a table | create the new table, dual-write and backfill, or keep the old name and set schema "old_name" |
Add a NOT NULL column | add 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_nilfilter makes a re-run continue where it stopped. Tested: 2M rows in about 11 s. - Use the table name (
"posts"), neverMyApp.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_migrationsand run them withmix ecto.migrate --migrations-path priv/repo/data_migrations, orEcto.Migrator.run(repo, Ecto.Migrator.migrations_path(repo, "data_migrations"), :up, all: true)from your Release module. They shareschema_migrations, somix ecto.migrationslists 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-essentialsskill.
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/1andflush()can't run backward insidechange/0.flush()raisescalling flush() inside change when doing rollback is not supported, so writeup/0anddown/0.@disable_ddl_transactionmeans 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 1applies one migration andmix ecto.rollbackreverts one by default (--step n,--to version,--all). In production, roll back with the Release module'srollback/2.
Tooling
mix ecto.migrate --log-migrations-sqlprints the SQL each migration command generates.--log-migrator-sqlalso prints the migrator's ownbegin/LOCK TABLE/advisory-lock statements. Run them against a dev copy before shipping.mix ecto.migrationsshows which migrations are up and which are down.- Hex linters such as
excellent_migrationsandstrong_migrationsflag 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
- Use
cast_assoc/3/cast_embed/3for children edited with their parent — never insert children in a separate step; Ecto sets the foreign key - Child changesets never cast or require the parent's foreign key —
cast_assocsets it after the parent is inserted; requiring it gives "can't be blank" on_replaceis an option on the association, not oncast_assoc—has_many :items, Item, on_replace: :delete. The default is:raise: omitting an existing child from the params raises- Load the parent through the scope and preload before casting —
cast_assoc/3raises on%Ecto.Association.NotLoaded{} - Edit child lists from
<.inputs_for>with:sort_param/:drop_param— pluson_replace: :delete, and awith:function of arity 3 when order must persist Repo.transact/2+withfor a fixed set of steps;Ecto.Multiwhen the steps depend on input (one step per cart item)- Never read-check-write a counter — decrement with
update_allguarded bywhere: p.stock >= ^qtyand check the affected count is 1 - Choose
on_deletedeliberately —:delete_allfor owned children,:nilify_all(nullable column) to keep them,:restrict+no_assoc_constraint/3to block; the default:nothingalso blocks the delete - 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 throughphx-change, so thevalidatehandler re-renders the list — no add/remove events needed.- The empty hidden
..._drop[]input outsideinputs_foris required: without it, removing the last child sends noingredientskey and nothing is deleted. - Both buttons need
type="button", or they submit the form. :drop_paramrequireson_replace: :deleteon the association. Forhas_many, persisted order needs thepositionfield set by the arity-3with:(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_allskip changesets and autogenerated timestamps — setinserted_at/updated_atyourself (DateTimefor:utc_datetimeschemas).- They also don't turn constraint violations into errors: a bad foreign key in
insert_allraisesPostgrex.Errorout ofRepo.transact/2rather than returning{:error, ...}. Make failures you expect go through a step that returns{:error, reason}, asreserve/3does. - 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_delete | Deleting the parent… | Use for |
|---|---|---|
:delete_all | deletes the children | Owned children: line items, ingredients, replies |
:nilify_all | sets the FK to NULL (column must allow it) | Keep the child, drop the link: author, team |
:restrict | fails while children exist | Parents 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
- Preload in the context, once for the whole list. Use
preload:in the query or oneRepo.preload(list, ...). Never callRepo.preload,Repo.getor a context function per row, whether inEnum.map, a HEEx:foror a JSON view. - Use separate-query preloads by default. Join-preload only a
belongs_to/has_onethat you also filter or sort on. Joining ahas_manymultiplies rows, andlimitthen counts children instead of parents. - A
limitin a preload query is global, not per parent. For "latest N per post", use arow_number()window restricted to the parents' ids. - Count and check without loading rows. Use
Repo.aggregate(q, :count),Repo.exists?/1,group_by+count(), orselect_mergeinto a virtual field. Neverlength(Repo.all(q)). - Compose with named bindings and
dynamic/2. Putas:on joins and usewith_named_binding/3so a join is added only once. For "has any child", useexists/1withparent_as/1instead of a join plusdistinct. - Run
Repo.streamonly insideRepo.transact. The function must return{:ok, _}, the transaction needstimeout: :infinity, and streams don't support preloads. For long jobs, batch by keyset (where: p.id > ^last_id), neverOFFSET. - Never read-modify-write a counter or balance. Use
update_all(inc: ...), a conditionalupdate_all,lock: "FOR UPDATE"insideRepo.transact, oroptimistic_lock/3withstale_error_field:. insert_allandupdate_allbypass changesets. Nothing is validated and no timestamps are generated. Setinserted_at/updated_atyourself, and chunk so rows × fields stays under Postgres's 65,535 parameters.- 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. - Tenant isolation comes from the scope, passed explicitly.
prepare_query/3is 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()
| Use | When |
|---|---|
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_many | A 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/1is in theecto-essentialsskill. Unescaped%or_in a search term match everything.exists/1takes a query directly, as inexists(from c in Comment, ...).exists(subquery(...))also compiles. It must reference the outer row throughparent_as(:post), so the outer query needsas: :post. Usenot exists(...)for "posts with no comments".has_named_binding?/2returns whether a binding exists, andwith_named_binding/3adds a binding only if it is missing. The join above runs at most once, however many filters need it.- Use
subquery/1to aggregate first and then join, as in the comment counts above. Joining the raw children and then usinggroup_byon 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 iscount(*).count(c.id)skips NULLs, which matters with aleft_join.Repo.aggregate/3dropsorder_byand preloads, and wraps a query that haslimit,offsetordistinctin a subquery, soRepo.aggregate(from(p in Post, limit: 2), :count)returns 2, not the table count. It raises on a query withgroup_by; use thegroup_by+selectform above.- Use
Repo.exists?/1forif count > 0checks. 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/2raisesArgumentErrorunless the function returns{:ok, _}or{:error, _}. TheRepo.streamdocs' own example returnsEnum.to_list(stream)and would hit this error.preload:on a streamed query raisespreloads are not supported on streams. Chunk the stream and callRepo.preload/2per chunk, as above.max_rowsdefaults to 500. The transaction's default 15 s timeout applies to the whole stream, so passtimeout: :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 raisesEcto.StaleEntryError. With it, the update returns{:error, changeset}withlock_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_alldoesn't autogenerateinserted_at/updated_at, or any field except an:id/:binary_idprimary key. Withnull: falsecolumns, leaving them out fails withnot_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 setuser_idfrom 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 bydiv(65_535, fields_not_in_placeholders). Smaller chunks (1k–5k rows) keep locks and memory reasonable. returning:returns structs for the rows written. Withon_conflict: :nothing, skipped rows are not returned. With{:replace, fields}, updated rows are returned too.conflict_targetmust match a unique index exactly. Never include the conflict-target columns in{:replace, ...}. Upserts through a changeset (Repo.insert/2) are covered in theecto-essentialsskill.
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/3is the same asEcto.Adapters.SQL.explain(Repo, ...). It takes:all,:update_allor:delete_all, and the Postgres optionsanalyze,verbose,costs,settings,buffers,timing,summary,format(:text,:map,:yaml) andplan.analyze: trueexecutes the query. By default it runs inside a transaction that is rolled back, so analyzingupdate_allis safe. Inside your ownRepo.transact, that forced rollback aborts your transaction. Passwrap_in_transaction: falsethere. 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 thetelemetry-essentialsskill. For copy-pasteable SQL with inlined params in dev, theecto_dev_loggerpackage replaces the default logger: setlog: falseon the repo in dev and callEcto.DevLogger.install(MyApp.Repo).
Indexes for the queries you run
| Query shape | Index |
|---|---|
where user_id = ? order by published_at desc | index(:posts, [:user_id, :published_at]): equality columns first, then the sort or range column |
Same, plus is_nil(p.deleted_at) on every read | index(: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 table | index(: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) cursor | index(: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 forinsert,updateordeleteof 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
scopeand pass it as an option. Don't store it in the process dictionary fordefault_options/1to read: it is invisible in the code, and it is lost in parallel preloads,Tasks and LiveViewassign_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
- Branch with multi-clause functions, pattern matching and
case— never nestif;unlessis soft-deprecated, writeif !cond - A fallible function returns
{:ok, value} | {:error, reason}on every path — never a bare value from one clause and a tuple from another - Error reasons are atoms (or a changeset), not strings — translate them to messages at the edge (controller, LiveView)
- End a
withon the last call itself, and no catch-allelse—{:ok, x} <- f() do {:ok, x} endis redundant (CredoRedundantWithClauseResult) - Multi-step writes go inside
Repo.transact/2— awithalone does not roll back the first write when a later step fails - Call
!functions only when failure is a bug — never wrap a bang call intry/rescue; call the non-bang version andcaseon it - A struct pattern matches
nilfields —%User{name: name}bindsnil; addwhen is_binary(name)when you rely on the value - Treat compiler type warnings as bugs — fix the code; don't add guards or
_ =just to silence them - Logging: put values you'll filter on in Logger metadata; a human-readable message may interpolate — every module that logs has
require Logger @impl trueon every callback, clauses of one function grouped together — split clauses fail--warnings-as-errors, and so does a callback without@implonce 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!/2are right when a missing record should 404: phoenix_ecto mapsEcto.NoResultsErrorto a 404 page. Use the non-bang version pluscasewhen absence is a normal outcome.- Reserve
try/rescuefor code you don't control that only raises (no tuple-returning variant exists).
Pattern-matching traps
%{}matches any map, not an empty one; usemap_size(m) == 0.- Params and decoded JSON have string keys: match
%{"id" => id}. NeverString.to_atom/1on input (atoms are never garbage collected); map strings to atoms explicitly or useString.to_existing_atom/1. map.keyraisesKeyErrorwhen the key is missing;map[:key]returnsnil. Structs don't implementAccess, so usestruct.key.==,<and>onDateTime,Date,Decimalcompare struct fields, not values. UseDateTime.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/withclauses, and warns on redundant clauses. A type warning is a proven bug or dead code: fix the code. Keepmix compile --warnings-as-errorsin CI. dbg/1prints each step of a pipeline with its result. Remove before committing (Credo's defaultWarning.Dbgcheck flags it).then/2pipes into a non-first argument;tap/2runs 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/1returns{: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 byjson/2or channels, implement the configured library's protocol (@derive {Jason.Encoder, only: [...]});@derive JSON.Encoderalone isn't used by Phoenix. Plain decoding can use either.mix format --migraterewrites 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]beforedefstructturns a missing key into a compile error. Write@specon public functions for docs and Dialyzer; the 1.20 checker infers types without them. defguardmakes 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 of5 * 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
- 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{}. - 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}, andReq.get!/2doesn't raise on them either. Use bang functions only where a crash is fine (scripts, seeds, mix tasks). - Know the default retry.
retry: :safe_transientretries 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 obeysRetry-Afterwith no upper limit. Cap that delay, and lowermax_retrieson user-facing paths. retry: falseinside Oban workers. Oban already retries the job with backoff; Req retries on top multiply the attempts and hold the queue slot while they sleep.- 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. Thenretry: :transientis safe. - Set every timeout on purpose. Connect (5 s by default),
receive_timeout(15 s per read),request_timeout(total time, new in 0.7), andfinch: [pool_timeout: ...]. Never block a LiveView event handler on a slow API: usestart_async. - Expect bodies of any shape.
json:encodes with Jason. Responses are decoded bycontent-typeinto maps with string keys. A malformed JSON body is{:error, %Jason.DecodeError{}}, and an HTML error page from a proxy stays a binary. - Never fetch a user-supplied URL without a host allowlist and
redirect: false. On a redirect to another host, Req drops onlyauthorization, so custom API-key headers go along. Never log request headers or bodies, and never useverify: :verify_none. - Test with
plug: {Req.Test, MyApp.Client}andretry: falseinconfig/test.exs. Use Mox only at a behaviour boundary, when callers shouldn't see HTTP at all. - 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: combiningfinch:withconnect_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.exsruns. - Option names are validated.
Req.new(bas_url: ...)raisesArgumentError("Did you mean :base_url?"). Custom options needReq.Request.register_options/2(see the reference). - Merging:
Req.merge/2and per-call options mergeheadersandparamsand override everything else. Options passed later win, so a caller'sretry: falsebeats 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!()} endis evaluated on every attempt. So is{mod, fun, args}. - Version check: Phoenix 1.8 generates
{:req, "~> 0.5"}. A freshmix deps.getresolves that to 0.7.x, but an oldermix.lockmay still pin 0.5. Several options changed; see Upgrading from 0.5.
Retries
retry: :safe_transient (default) | |
|---|---|
| Methods | GET, HEAD (:transient retries every method) |
| Responses | 408, 429, 500, 502, 503, 504 |
| Exceptions | Req.TransportError with :timeout, :econnrefused, :closed; HTTP/2 :unprocessed, :pool_not_available |
| Attempts | max_retries: 3, so up to 4 requests in total |
| Delay | exponential 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/1in the caller. ARetry-After: 3600freezes a controller request or a LiveView for an hour. - Setting
retry_delaymakes Req ignoreRetry-After(changed in 0.7). To keep honouring the header with a ceiling, pass a 2-arityretryfunction that returns{:delay, ms}. - Retries log at
:warningby default. Useretry_log_level: falseto 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-Keyis common). Check how long they keep keys.
Timeouts
| Option | Default | Bounds |
|---|---|---|
connect_options: [timeout: ms] | 5_000 (Finch's default; Req's docs say 30 s) | TCP + TLS connect |
receive_timeout: ms | 15_000 | each socket read; a slow trickle can run far longer in total |
request_timeout: ms (0.7) | :infinity | the whole response; HTTP/1 only, best effort |
finch: [pool_timeout: ms] | 5_000 | waiting 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 singleReq.getcan take over a minute. - On user-facing paths, set tight values and few retries. In LiveView, run the call in
start_async/3orassign_async/3(see thephoenix-liveview-essentialsskill). - Each distinct
connect_optionsvalue starts its own Finch pool, and Req never stops it. Keep the value constant per client, never computed per request.
JSON bodies
- Encoding:
json: datacallsJason.encode_to_iodata!/1and setscontent-typeandaccepttoapplication/json. Req 0.7 depends on Jason, not Elixir'sJSONmodule:@derive JSON.Encoderdoesn't help, and a struct needsJason.Encoderor raisesProtocol.UndefinedError. Build plain maps. - Decoding: the default
decoders: [:json, :json_api]picks the decoder from the responsecontent-typeand usesJason.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-typewith an invalid body returns{:error, %Jason.DecodeError{}}, even for a 200. decode_body: false(ordecoders: false, orraw: 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 deprecateddecode_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.254or internal services. Check scheme and host against an allowlist, then request withredirect: false; a redirect is a new, unchecked URL. The full pattern, including DNS-rebinding notes, is in thesecurity-essentialsskill. - Redirects and credentials: when a redirect changes host, scheme or port, Req removes the
authorizationheader and the:authoption (unlessredirect_trusted: true). Custom headers such asx-api-keyare forwarded. For APIs authenticated that way, useredirect: falseor check thelocationyourself. - Logging:
inspect(%Req.Request{})masksauthorizationand:auth, but not other headers, and nothing masks bodies. Log the API name, the status andException.message/1, neverresp.bodyorreq.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, usetransport_opts: [cacertfile: path]. - Logger metadata conventions and filtering are in the
telemetry-essentialsskill.
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: ...]withconnect_options:raises "cannot set both :finch and :connect_options". Put connect settings in the pool'sconn_opts.finch: [name: MyApp.Finch, size: 5]raises too: pool options belong where the pool is started.- The 0.5 form
finch: MyApp.Finchstill works but prints a deprecation warning. - With
plug:in test config, Req uses theReq.Plugadapter 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, andconn.body_params. TheReq.Plugadapter runsPlug.Parsersfor JSON, form and multipart bodies. UseReq.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")beforesend_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).
- an error status with a JSON body:
- 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 needReq.Test.allow(MyApp.Weather, self(), pid). If you can't get the pid, usesetup {Req.Test, :set_req_test_to_shared}withasync: 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. Addfinch_private: %{api: :weather}to the client and it shows up asmeta.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_req1.0 attaches cleanly on Req 0.7). Exporter setup is in thetelemetry-essentialsskill. - 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
:fusechecks the fuse in a request step (Req.Request.halt/2when 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 theRetry-Aftervalue. 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 owncache: truestep is deprecated since 0.7.1.
Upgrading from Req 0.5
| 0.5 | 0.7 |
|---|---|
finch: MyFinch | finch: [name: MyFinch] |
pool_timeout: ms | finch: [pool_timeout: ms] |
decode_json: [keys: :atoms] | decoders: [json: &Jason.decode(&1, keys: :atoms)] |
retry_delay: and Retry-After both apply | setting retry_delay ignores Retry-After |
| zip/tar/gz/csv decoded automatically | only JSON; opt in with decoders: (0.6) |
| compressed responses requested by default | compressed: true to opt in (0.6.1) |
run_finch / put_plug steps | Req.Finch / Req.Plug adapter modules |
cache: true | deprecated (0.7.1) |
| retry delays without jitter | jitter 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
use Oban.Workerwith explicitqueue:andmax_attempts:, and match string-keyed args inperform/1- 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 - Enqueue in the same transaction as the data the job needs —
Oban.insert/2insideRepo.transact/2, orOban.insert/3in anEcto.Multi; handle the result (noOban.insert!in app code) - Make workers idempotent — a job can run more than once (retries, Lifeline rescues); record completion and send an idempotency key to external APIs
- Uniqueness keeps
:workerinfields— omitfields(default[:args, :queue, :worker]) or use[:worker, :args]; narrow withkeys:, pick a state group such as:incomplete.Oban.insert_all/2ignoresuniquein OSS - One
config :my_app, Obanblock with the 2.24 service keys —cron:,pruner:,lifeline:; always enableprunerandlifeline - Args hold IDs and small JSON values only — fetch fresh data in
perform/1 - Bound every job —
timeout/1for long work; outbound HTTP usesretry: falseand a host allowlist; cap snoozes withmeta["snoozed"] - Test with
Oban.Testing—testing: :manual,perform_job/3,assert_enqueued,drain_queue; never callperform/1directly - 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/1isRepo.get(User, id), which you add; the generator only hasget_user!/1, which would raise (and retry) for a deleted user instead of cancelling.max_attemptscounts the first run (5 = 1 + 4 retries). Retries back off exponentially (15 s minimum, with jitter) unless you definebackoff/1.argsare 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_inis the documented name since 2.24;schedule_instill works) orscheduled_at: datetime. - Unique conflicts are not errors:
Oban.insert/2returns{:ok, %Oban.Job{conflict?: true}}for a duplicate. - Bulk:
Oban.insert_all/2(orOban.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; useOban.insert/2per 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:andreindexer:are top-level keys since 2.24 (Oban.Plugins.Cronis nowOban.Cron, and so on). The oldplugins: [...]form still works.- Keep the Oban config in one
configcall. Repeated calls deep-merge keyword lists, but aplugins:list containing one bare module (Oban.Plugins.Lifeline) isn't a keyword list, so a laterplugins:replaces it and cron or pruning silently disappears. - Lifeline is off unless configured. Without it, jobs orphaned in
executingby a node restart stay there forever. It rescues purely by time, sorescue_aftermust exceed your longest job'stimeout/1, or it re-runs jobs that are still executing. - Pruner keeps
oban_jobsfrom growing without bound;max_ageaccepts{7, :days}. - Start Oban in
application.exwith{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/1returns milliseconds and defaults to:infinity. A timed-out job fails withOban.TimeoutErrorand is retried like any error.backoff/1returns 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]
fieldsdefaults to[:args, :queue, :worker]. Listing[:args]alone makes jobs from different workers with the same args collide.statesgroups (2.20+)::successful(default: everything except cancelled/discarded, so a completed job blocks duplicates for the wholeperiod),: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 uncappedRetry-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 thehttp-clients-reqskill.- Match every status: a
casewithout a fallback clause raisesCaseClauseErroron the first unexpected status. - Snoozes (2.24): a snooze no longer consumes an attempt, so
max_attemptscan't stop a job that keeps snoozing, andattempt-based delays stay constant. Count snoozes withmeta["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/3stringifies args, validates the worker's options, checks the return value, and accepts job options such asattempt: 10ormeta: %{"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, ...}; addwith_recursion: truewhen jobs enqueue jobs andwith_scheduled: trueto include scheduled ones.Oban.Testing.with_testing_mode(:inline, fn -> ... end)runs jobs immediately inside one test;assert_enqueuedcan'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
- Always use
@impl truebefore GenServer/Supervisor/Agent callbacks - Keep
init/1fast — return{:ok, state, {:continue, term}}and do DB/network setup inhandle_continue/2; a slowinitblocks the supervisor and app boot - Default to
GenServer.call— it gives back-pressure and a 5 s timeout. Usecastonly for cheap state updates you can afford to lose; send slow side effects (email, HTTP) toTask.Supervisoror Oban - Wrap every process behind a public API module — callers never write
GenServer.call(pid, ...)themselves - One argument shape:
start_link(opts)with a keyword list — read it withKeyword.fetch!/2; child specs pass{MyApp.Room, room_id: id} - Registry for dynamic processes; atoms only for singletons — never build a name with
String.to_atom/1 - Every long-running process is supervised — no bare
spawn/Task.start; inside a LiveView usestart_async/3orassign_async/3 - Every
Task.asyncis awaited — for collections useTask.Supervisor.async_stream_nolink/4withon_timeout: :kill_task - Don't rely on
terminate/2for 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/3waits 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)).castreturns immediately, gives no back-pressure (a flooded mailbox grows without bound), and the message is lost if the server crashes. Fine forincrement; 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/1links the task to the caller: if the task crashes, so does the caller. UseTask.Supervisor.async_nolink/2when the caller must survive.- Plain
Task.async_stream/3defaults toon_timeout: :exit, which crashes the caller on the first slow item. - In a LiveView, use
start_async/3+handle_async/3(orassign_async/3), neverTask.async: LiveView supervises the task, cancels it when the user leaves, and turns crashes into{:exit, reason}. See thephoenix-liveview-essentialsskill.
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 inMyApp.Roomabove. - 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 useTask.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
- 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.8Usermodule orUserAuthover the generated one. - Never edit the generated auth migration — add a new migration for each new column.
- Add a
registration_changeset/3that pipesemail_changeset/3— 1.8 has no registration changeset:register_user/1usesemail_changeset/3, which the settings page also uses to change email. Requiring a new field insideemail_changesetbreaks email changes. - 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/1raises for unconfirmed users with a password (see "Mixing magic link and password registration" inmix help phx.gen.auth). - Add only the new line to the schema — keep
field :authenticated_at, :utc_datetime, virtual: true(sudo mode reads it) andtimestamps(type: :utc_datetime). - Use the generated fixtures; add the new field to
valid_user_attributes/1—user_fixture/1already confirms the user via a magic link;unconfirmed_user_fixture/1,user_scope_fixture/0,1andset_password/1already exist. - Never
castprivileged fields —:role,:confirmed_at,:org_id,:hashed_passwordare set withchange/2/put_change/3in a dedicated context function, never from form params. - Uniqueness = unique index +
unique_constraint— plusunsafe_validate_uniquefor early feedback, skipped duringphx-changevia the generator'svalidate_unique: falseoption. - Update every caller of the changed changeset — the registration LiveView's
mountand"validate"handler,register_user/1, and the generatedaccounts_test.exstests that callregister_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.exlib/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 + templatestest/support/fixtures/accounts_fixtures.exand tests for all of the above- a
config :my_app, :scopesentry so laterphx.gen.live/phx.gen.contextruns generate scoped code (see thephoenix-scopes-and-generatorsskill)
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
- Pass
current_scopeas the first argument to every context call —Blog.get_post!(socket.assigns.current_scope, id), neverBlog.get_post!(id)orRepo.get!(Post, id)with an id from params. Loading by a client id without the scope is an IDOR. - Scope the query, not just the check —
get_post!(%Scope{} = scope, id)isRepo.get_by!(Post, id: id, user_id: scope.user.id): another user's record raisesEcto.NoResultsError(a 404), so existence isn't leaked and no separate check can be forgotten. - 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. - Authorize in
handle_params/3as well asmount/3—push_patchre-runshandle_paramsbut notmount; load any record whose id arrives in the URL through the scope where the params arrive. - Authorize every
handle_event/3on the server — hiding a button is UX, not security; events can be crafted with any params. - Never
castownership or privileged fields —:user_id,:org_id,:role,:confirmed_at,:deleted_at. Set them withput_change/3orEcto.build_assoc/3from the scope, as the generator'schangeset(post, attrs, scope)does. - Policies take
%Scope{}, not%User{}— the scope is what the web layer has, and it can carry org and role. - Put roles and orgs on the
Scopestruct — extend the generatedScope(its moduledoc says to) and fill it once in anon_mounthook / plug, instead of threading extra arguments. - Scope PubSub topics too — subscribe and broadcast on
"user:#{scope.user.id}:posts"(the generator'ssubscribe_posts(scope)), never a global topic. - 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
- Authenticate in
connect/3; return:errorotherwise. Same-origin browser clients can reuse the phx.gen.auth session throughconnect_info: [session: @session_options]; other clients use aPhoenix.Tokenverified with an explicitmax_age(keep it short, e.g.86_400; it can't be revoked). - Make sockets disconnectable on logout.
id/1returns a topic you can broadcast"disconnect"to. With session auth, return the session'slive_socket_idand the generatedlog_out_user/1already does it. - Authorize in
join/3through the scope — load the topic's resource withsocket.assigns.current_scopeand return{:error, %{reason: "unauthorized"}}if that fails. The topic string is client input. - Keep
check_originon 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 bothcheck_originandcheck_csrfarefalse. - Keep channel modules thin — delegate to context functions that take the scope.
- 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"). - Use
intercept/handle_outonly to filter or customize a broadcast per subscriber. An intercepted event is encoded once per subscriber instead of once per topic. - Use
Phoenix.Presencefor who's online, in channels and LiveViews. In channel tests,assert_push "presence_state", _before you readPresence.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).
| Call | Goes 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
| Channels | LiveView | PubSub | |
|---|---|---|---|
| Client | Any (mobile, SPA, IoT) | Browser | Server processes only |
| Rendering | Client | Server | None |
| Use when | Non-browser clients, custom protocols | Browser UI with real-time updates | Process-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
- Use the
:apipipeline —plug :accepts, ["json"], no session, CSRF or browser headers; API clients authenticate with tokens - Pass
conn.assigns.current_scopeas 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 - Follow
phx.gen.json—action_fallback,render(conn, :show, post: post)with aPostJSONmodule,ChangesetJSONfor validation errors;json/2is fine for one-off bodies - The
FallbackControllerhandles every error your contexts return, plus a catch-all 500 — an unmatched{:error, _}otherwise raisesFunctionClauseError; never putinspect(reason)in the response body - Never return unbounded collections — parse
page/per_pagewithInteger.parse/1and clamp (1..100); order by a unique tiebreaker (desc: p.id); use keyset pagination for large or fast-changing tables - Bearer tokens are random, stored hashed, expire, and are revocable — follow the generated
UserTokenpattern; never store or compare plaintext tokens - 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/2already callsBcrypt.no_user_verify/0for unknown users - Preload every association the JSON view renders — in the context function, not the view;
post.useron an unloaded association is%Ecto.Association.NotLoaded{}(and the generatedPosthas nobelongs_to :useruntil you add one) - Version via URL prefix (
/api/v1) — noas: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
OPTIONSrequests get an answer before routing:
Neverplug Corsica, origins: ["https://app.example.com"], allow_headers: ["authorization", "content-type"], allow_methods: ["GET", "POST", "PUT", "PATCH", "DELETE"]origins: "*"on an API that reads cookies. - Body size —
Plug.Parsersdefaults tolength: 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-Keyheader, 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
operationmacros (use OpenApiSpex.ControllerSpecs), and itsOpenApiSpex.Plug.CastAndValidateplug 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
- Use the generated
UserAuth; don't rewrite it —mix phx.gen.authalready ships the plugs,on_mounthooks, token reissue, remember-me and socket disconnects. Add routes to itslive_sessionblocks; don't re-typemount_current_scopeor paste pre-1.8 snippets over it. - Use the generated names exactly —
on_mounthooks are:mount_current_scope,:require_authenticatedand:require_sudo_mode; the router'slive_sessions are:current_userand:require_authenticated_user; the plug is:require_authenticated_user. There is no:require_authenticated_userhook and no:redirect_if_authenticatedhook. - Put login-only LiveViews inside the existing
live_session :require_authenticated_user— its scope pipes through the:require_authenticated_userplug (HTTP render) and runs the:require_authenticatedhook (websocket mount and live navigation). Alive_sessionname may be defined only once in the router. Create a separate one only when its LiveViews need extraon_mounthooks (see below). - For guests
@current_scopeisnil—Scope.for_user(nil)returnsnil, not an empty scope. Guard with@current_scope && @current_scope.user(or:if={@current_scope}). - Never make
/users/log-inguest-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 underlive_session :current_user; registration redirects logged-in users from its ownmount/3. - Gate sensitive pages with
:require_sudo_mode—on_mount {MyAppWeb.UserAuth, :require_sudo_mode}in the LiveView (inside the authenticatedlive_session; it dereferencescurrent_scope.user), and re-checkAccounts.sudo_mode?/2in the action that changes credentials. - Disconnect live sockets when sessions die —
log_out_user/1broadcasts"disconnect"to the session'slive_socket_id; after anyAccountscall that returns expired tokens, callUserAuth.disconnect_sessions(tokens). Never drop:live_socket_idfrom the session. get_user_by_session_token/1returns{user, token_inserted_at}ornil— destructure the tuple; never wrap it in a scope directly.- In
on_mounthooks, fully qualifyPhoenix.LiveView.redirect/2andPhoenix.LiveView.put_flash/3—UserAuthimportsPhoenix.Controllerfor its plugs; excluding those imports breaks the plug half. - 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}}}fromlive/2.
What the Generator Gives You
mix phx.gen.auth Accounts User users --live (Phoenix 1.8):
| Piece | Name | Used for |
|---|---|---|
Plug (in :browser) | :fetch_current_scope_for_user | assigns :current_scope on every request (nil for guests) |
| Plug | :require_authenticated_user | redirects to ~p"/users/log-in", stores :user_return_to |
on_mount | :mount_current_scope | assigns :current_scope on the socket |
on_mount | :require_authenticated | halts with redirect to log-in when no user |
on_mount | :require_sudo_mode | halts unless the user authenticated in the last 10 minutes |
live_session | :current_user | register, log-in, magic-link confirmation (optional auth) |
live_session | :require_authenticated_user | settings (login required) |
| Function | disconnect_sessions/1 | broadcasts "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 toUserSessionController.create, which callsAccounts.login_user_by_magic_link/1. - The first magic-link login confirms the user and expires all their tokens;
login_user_by_magic_link/1returns{:ok, {user, expired_tokens}}and the controller callsUserAuth.disconnect_sessions(expired_tokens).update_user_password/2does the same. log_out_user/1deletes the session token and broadcasts"disconnect"tolive_socket_id("users_sessions:" <> encoded token), so every open LiveView on that session (other tabs too) drops and re-runs itson_mounthooks 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
@impl truebefore every callback —mount,handle_params,handle_event,handle_info,handle_async,render.- Pass
socket.assigns.current_scopeas the first argument to every context call —Blog.get_post!(scope, id), neverBlog.get_post!(id). Loading, updating or deleting by a client-supplied id without the scope is an IDOR. LiveViews call contexts, neverRepo. - Set every assign
render/1reads before the first render — static defaults inmount/3, URL-dependent ones (filter, sort, page) inhandle_params/3. - Subscribe and start timers in
mount/3insideif connected?(socket)— never inhandle_params/3, which re-runs on everypush_patchand stacks duplicate subscriptions. - Load slow data with
assign_async,stream_asyncorstart_async— not withif connected?(socket)branches or blocking queries inmount/3. - Collections are streams —
stream/4,stream_insert/4,stream_delete/3,stream(..., reset: true)to refilter. The container needs anidandphx-update="stream". - Forms:
to_form/2into@form;<.form for={@form} id="..." phx-change="validate" phx-submit="save">;<.button>directly inside the form (<.form>declares onlyinner_block— an actions slot is silently dropped, so the button never renders). Validate withto_form(changeset, action: :validate). - Expected failures don't crash — on
{:error, %Ecto.Changeset{}}re-assign the form; let only bugs raise. - Function components declare
attr/slot, withdefault:for optional attrs — neverMap.get(assigns, :x, default)orassigns[:x]. - HEEx:
{@x}in text and attributes,:for/:ifattributes,<%!-- --%>comments; add:keyto:forover plain lists. - JS: reach for
Phoenix.LiveView.JScommands first, then colocated hooks; everyphx-hookelement needs a unique DOMid. - 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
Enumover@streams.posts. Keep counts or "is empty" state in a separate assign, or use theonly:CSS trick above. stream(socket, :posts, items, reset: true)replaces the client list (refiltering, pagination).limit: -50keeps the last 50.stream_delete(socket, :posts, post)needs the struct; with only a DOM id usestream_delete_by_dom_id/3.- Small, bounded lists (tabs, a few options) can stay plain assigns. Give the comprehension a
:keyso 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
| Call | Use 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/2also accepts a plain map for schemaless forms:to_form(%{"q" => ""}, as: :search). action: :validateis what makes errors show duringphx-change; without an action the changeset's errors are hidden.used_input?/1hides 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 aboutphx-changeforms without one. phx-debounce="300"(ms) or"blur"on inputs that trigger server work;phx-throttlefor 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 aPhoenix.LiveView.AsyncResult(.ok?,.loading,.failed,.result).stream_async(socket, :name, fn)— the fn returns{:ok, enumerable}or{:ok, enumerable, stream_opts};@streams.nameexists immediately and@nameholds theAsyncResult.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-mountedruns 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(withphx-key),phx-blur/phx-focuscover 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
| Mistake | Fix |
|---|---|
Blog.get_post!(id) / Repo.get(Post, id) in a LiveView | Blog.get_post!(socket.assigns.current_scope, id) |
PubSub.subscribe in handle_params | Subscribe 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 id | id="post-form" |
socket.assigns.x inside an assign_async fn | Bind x = socket.assigns.x before the fn |
if connected? around an expensive load | assign_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 reload | It swaps LiveViews over the socket; redirect/2 reloads |
Element with phx-hook and no id | Add 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
- 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. - Wrap topics in context functions that take the scope —
Blog.subscribe_posts(scope)and a privatebroadcast_post(scope, message). LiveViews never build topic strings. - Broadcast from contexts, after the write succeeds. LiveViews only subscribe and react.
- Subscribe in
mount/3behindif connected?(socket). The disconnected render is a short-lived process. Subscribing inhandle_params/3adds a duplicate subscription on everypush_patch. - Handle PubSub messages in
handle_info/2and match the payload struct ({type, %Post{}} when type in [...]), as the generators do. - Collections are streams. Re-stream with
stream(socket, :posts, list_posts(scope), reset: true)(whatphx.gen.livedoes), or apply one change withstream_insert/4/stream_delete/3. - Subscribing to a single record's topic needs a scoped load first —
get_post!(scope, id)before subscribing to"post:#{post.id}". - 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
| Topic | Who 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
| Function | Delivers to |
|---|---|
Phoenix.PubSub.broadcast/3 | every subscriber on every node |
Phoenix.PubSub.broadcast_from/4 | everyone except the given pid (skip the sender's own LiveView) |
Phoenix.PubSub.local_broadcast/3 | subscribers on this node only |
MyAppWeb.Endpoint.broadcast/3 | channel 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
- Check
config :my_app, :scopesbefore generating. Generators read it at mix-task time; with no default entry (nophx.gen.authyet) they silently emit unscoped contexts with no PubSub topic and no owner column. Runphx.gen.authfirst, or add the entry. - Take the default scope unless the data is truly global.
--no-scope(lookup tables, public content) drops the scope argument, the owner column, thesubscribe_*/broadcast_*functions and the cross-scope tests.--scope nameonly accepts a configured entry, and combining the two flags raises. - Don't pass the owner as a field. With the default scope,
user_id:references:usersaborts the generator ("same name as the scope schema key"); the scope already addsfield :user_idand the migration column. - Keep the generated ownership checks.
update_*,delete_*andchange_*all start withtrue = post.user_id == scope.user.id. A hand-written "new" form must build%Post{user_id: scope.user.id}, orchange_post/2raisesMatchError. - Extend the one
Scopestruct; 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 samemoduleandassign_keywith a differentaccess_pathandschema_key. - Fill extra scope fields with a plug and an
on_mounthook. 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. - Write the test helpers before generating against a new entry. Generated tests call
<name>_scope_fixture/0fromtest_data_fixtureandsetup :<test_setup_helper>. Both must exist, and the setup helper must returnscope:. - Scoped controllers need a pipeline that assigns the scope.
phx.gen.jsonoutput readsconn.assigns.current_scope, but the generated:apipipeline never sets it, so every action fails withKeyError. - 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. - 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):
| Key | Drives |
|---|---|
default | used when no flag is given; only one entry may be true (more raises) |
module | the struct pattern-matched in context heads (%Scope{} = scope) |
assign_key | socket.assigns.current_scope / conn.assigns.current_scope in generated web code |
access_path | the owner value: [:user, :id] becomes scope.user.id in queries, put_change and topics |
schema_key | the owner field added to the schema and migration (:user_id) |
schema_type | that field's type (:id, :binary_id) |
schema_table | references(:users, on_delete: :delete_all); nil gives a plain column with no FK |
schema_migration_type | overrides the migration column type (defaults to schema_type unless it is :id) |
route_prefix | e.g. "/orgs/:org_slug", prepended to every generated path; at most one :param |
route_access_path | what fills that param, e.g. [:org, :slug] (defaults to access_path minus its last element) |
test_data_fixture | the module generated tests import <name>_scope_fixture/0 from |
test_setup_helper | the 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
| Command | Result |
|---|---|
mix phx.gen.live Blog Post posts title:string | default scope |
mix phx.gen.live Projects Project projects name:string --scope org | the org entry |
mix phx.gen.html Pages Page pages title:string --no-scope | unscoped |
--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(notbelongs_to) andchangeset(post, attrs, user_scope), which casts only your fields and ends withput_change(:user_id, user_scope.user.id). - Migration:
add :user_id, references(:users, on_delete: :delete_all)andcreate index(:posts, [:user_id]). - Context: every function takes
%Scope{}first.list_*usesRepo.all_by(Post, user_id: ...)andget_*!usesRepo.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 thephoenix-pubsub-patternsskill). - LiveViews and controllers: every context call passes
socket.assigns.current_scope, and layouts getcurrent_scope={@current_scope}. The router hint ends with "Ensure the routes are defined in a block that sets the:current_scopeassign". - Tests and fixtures:
post_fixture(scope, attrs \\ %{})andsetup :register_and_log_in_user. Context tests create posts under twouser_scope_fixture()scopes and assert thatget_post!(other_scope, id)raisesEcto.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, :idandput_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()andsetup :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-essentialsskill. - Context calling context: pass the same scope (
Billing.charge(scope, ...)), neverscope.useror 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:
- Scope module. Copy the 1.8
accounts/scope.ex(above, without the org fields). - Config. Add the
:scopesentry shown at the top (default: true, your fixture module, your setup helper name). - Assign
:current_scopenext 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
- Test helpers. Add
user_scope_fixture/0toAccountsFixtures, and haveregister_and_log_in_user/1returnscope: Scope.for_user(user)too. - Owner columns. Add
user_id(FK and index) to existing tables, backfill it, then make itNOT NULLbefore scoping their contexts. On tables with live traffic, follow the steps in theecto-migrations-safetyskill. - 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.
- 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: itsapp.html.heexis a layout using{@inner_content}, and itsbutton/1has no:variant. Port the 1.8Layouts.app/1andcore_components.exfirst, 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
| Symptom | Cause |
|---|---|
| Generated context has no scope argument | no default :scopes entry, or --no-scope |
KeyError :current_scope in a generated controller | its pipeline doesn't assign the scope (:api) |
undefined function org_scope_fixture/0 in generated tests | the helper for the new entry wasn't written first |
MatchError opening a "new" form | struct built without the owner (%Post{} instead of %Post{user_id: ...}) |
| Another user's records appear live | a global topic, or a hand-written broadcast that skips broadcast_* |
There can only be one default scope | two 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
- Wrap every page in
<Layouts.app flash={@flash}>, and passcurrent_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. - Tailwind is configured in
assets/css/app.css. There is notailwind.config.js. Keep@import "tailwindcss" source(none), and add an@sourceline for every directory outsidelib/my_app_webthat contains class names. Tailwind scans only the listed paths. - 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. - Use daisyUI's semantic colors rather than raw palette colors. Write
bg-base-100,text-base-content,btn-primary,text-errorand the*-contentpairs, notbg-white,text-gray-900ortext-red-600. The semantic colors switch with the light/dark theme; hard-coded colors don't. - Use
core_components.exfirst, 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 itsattr/slotdeclarations, includingvalues:andrequired:. - Passing
classto<.button>or<.input>replaces the default classes; it doesn't add to them.<.button class="w-full">losesbtn. Pass the full class list (class="btn btn-primary w-full") or add a variant. - Icons are
<.icon name="hero-…">with a literal name. The suffixes are none (outline 24),-solid,-miniand-micro.icon/1accepts onlynameandclass; any other attribute is a compile warning and isn't rendered. <.button>declares onlyhref 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 failsmix precommit(compile --warnings-as-errors). Addtypeto the button'sinclude:list.- Accessibility you add yourself: a
labelon every<.input>(a placeholder is not a label), anaria-labelon every icon-only button,<button>or<.link>for anything clickable (neverphx-clickon adiv), 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
| Piece | Where | What it is |
|---|---|---|
| Tailwind CLI | {:tailwind, "~> 0.5"} in mix.exs; config :tailwind, version: "4.3.3", my_app: [...] in config/config.exs | A 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.exs | A 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 CSS | assets/css/app.css | All Tailwind and daisyUI configuration |
| Dev watcher | tailwind: {Tailwind, :install_and_run, [:my_app, ~w(--watch)]} in config/dev.exs | Rebuilds on save |
| Aliases | assets.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
@sourcelist matters:source(none)means Tailwind scans exactly these paths and nothing else. Classes that live inlib/my_app/(for example, a helper module that returns class strings), in a component library underdeps/, or in a sibling umbrella app produce no CSS until you add a line for them. Write it relative toapp.css, as in@source "../../deps/my_ui_kit/lib";. Don't dropsource(none)to "fix" this: automatic detection starts from the project root. - Don't delete the
phoenix-colocatedimport. The file exists only aftermix compile. That is whyassets.buildstarts withcompile, and why the release Dockerfile runsmix compilebeforemix assets.deploy. If you runmix tailwind my_appon a fresh checkout, it fails withCan'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:followsdata-theme="dark", notprefers-color-scheme. The theme script sets that attribute for system-dark users too, sodark:works in both cases, but semantic daisyUI colors usually makedark: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"]}.falseandnilentries are dropped. - Icon names follow the same rule:
name={"hero-#{@icon}"}generates nothing unless that exacthero-…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.csswith@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 likebg-(--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>setsdata-themeon<html>before first paint. It readslocalStorage["phx:theme"]and falls back to"system", which followsprefers-color-scheme. It also setsdata-theme-source="system"or"user". - Each toggle button is
phx-click={JS.dispatch("phx:set-theme")}with adata-phx-theme="system|light|dark"attribute. The script listens forphx:set-themeand readse.target.dataset.phxTheme. - The script returns early if
<html>already hasdata-theme. To use a theme stored on the user, render it from the server inroot.html.heex:<html lang="en" data-theme={@current_scope && @current_scope.user.theme}>, wherethemeis a field you add to the user and isnilfor "system". Anilvalue 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 withdata-phx-theme="brand". Don't enable the built-inlight/darkthemes; their names collide with the custom ones.dark:utilities only match a theme nameddark.
Semantic classes to reach for:
| Need | daisyUI classes |
|---|---|
| Page and surfaces | bg-base-100 (page), bg-base-200 / bg-base-300 (raised or sunken), text-base-content, text-base-content/70 (muted) |
| Brand and status colors | bg-primary text-primary-content, text-error, bg-success text-success-content (always pair a background with its -content color) |
| Buttons | btn + btn-primary / btn-error / btn-ghost / btn-outline / btn-soft; sizes btn-sm, shapes btn-square, btn-circle |
| Form controls | input, select, textarea, checkbox, toggle, fieldset, label; error state input-error / select-error / textarea-error |
| Feedback | alert + alert-info / alert-success / alert-warning / alert-error, badge badge-*, loading loading-spinner, toast, skeleton |
| Layout and data | card 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
| Component | Key attrs and slots | Notes |
|---|---|---|
<Layouts.app> | flash (required), current_scope (default nil), inner block | Layouts 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 attrs | Shows 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/href | Renders <.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 slot | Each <.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 slot | Given a stream, it sets phx-update="stream" and derives row_id for you |
<.list> | item slot with title | Read-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 code | On 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-label | Name 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 reach | Keep 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
| Wrong | Right |
|---|---|
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 browser | Add @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 cards | bg-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 precommit | Add 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.app | One 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 compiling | mix assets.build (compiles first) or mix compile && mix assets.deploy |
An empty phx-update="stream" container with no message | Add <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
- 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, sox.htmlsent asimage/pngpasses. Sniff the magic bytes of the uploaded file and pick the extension from an allowlist keyed on the detected type. - Name files on the server —
Ecto.UUID.generate() <> allowlisted_ext. Never putentry.client_name(or any request param) in a path. - Store under a configured directory, not a cwd-relative
"priv/static/uploads".priv/staticis 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 ownPlug.Static(or use object storage via:external). - 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 allowlistedcontent_type,disposition: :attachmentandx-content-type-options: nosniff. - The
consume_uploaded_entries/3callback must return{:ok, value}or{:postpone, value}. Wrap the context result ({:ok, Media.create_image(...)}) and handle failures after consuming. - Render
upload_errors/1andupload_errors/2, and makeerror_to_string/1total — atoms,{:external_metadata_failure, _},{:writer_failure, _}, yourvalidator:reasons, and a catch-all. - Form markup is Phoenix 1.8: assign
:forminmount, give<.form>anid, put<.button>directly inside it (<.form>has noactionsslot), and use a plain<label for={@uploads.images.ref}>(1.8core_componentshas nolabel/1component). - Default to manual uploads. With
auto_upload: true,consume_uploaded_entries/3raises while any entry is still in progress; consume from aprogress:callback onceentry.done?. - External uploads need both halves: the
:externalfunction returns meta with an:uploadername, and that name must be registered inuploaders:on the JSLiveSocket.
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">
×
</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 underMyApp.Media.uploads_dir(), or thePlug.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.digestdoesn't help; it only fingerprints files that existed at build time. - Submit button doesn't render: it is inside an
actionsslot;<.form>only declaresinner_block, so the slot is dropped with just a compile warning. no uploader configured for S3in the browser console: theuploaders:option is missing onLiveSocket.
Security Essentials
Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026
RULES — Follow these with no exceptions
- Never use
String.to_atom/1on user input — atoms are never garbage collected;String.to_existing_atom/1raises on unknown input (a 500). Map known strings with acase - Never build SQL or identifiers from user input —
fragmentalready rejects interpolated strings at compile time; the real holes areRepo.query/SQL.querywith string interpolation and user-chosen columns (field(p, ^name),identifier(^name),order_by: ^...). Use$1parameters and allowlist columns with acase - 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 - Avoid
raw/1— HEEx escapes{@x}; if HTML is required, sanitize with HtmlSanitizeEx first - Keep secrets out of logs —
redact: trueon sensitive schema fields, extend:filter_parameters, and never pass tokens or credentials as Logger metadata or message text - Compare secrets with
Plug.Crypto.secure_compare/2— never==or a pattern match - Never
:erlang.binary_to_term/1untrusted bytes — it can build functions and atoms; use JSON, orPlug.Crypto.non_executable_binary_to_term(bin, [:safe]) - Give every signed token a purpose and an explicit
max_age—Phoenix.Token.verify(endpoint, "purpose", token, max_age: ...);Phoenix.Tokencan't be revoked, so use database tokens (phx.gen.authUserToken) for login sessions and API keys - Validate outbound URLs (SSRF) — allowlist scheme and host before
Req.get(url), and disable redirects - Production transport and headers — keep the generated
force_ssl(HSTS), and replace the default CSP, which only setsbase-uriandframe-ancestors - 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.Formatwas 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}withjavascript:alert(1)still runs. Validate that the scheme ishttp/httpsbefore storing user URLs. - Uploaded files are another XSS route: see the
phoenix-uploadsskill. 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.exssetsforce_ssl: [rewrite_on: [:x_forwarded_proto], ...]. That redirects HTTP to HTTPS and sends HSTS (1 year by default).force_sslis compile-time config: keep it inprod.exs, notruntime.exs.rewrite_onis required behind a TLS-terminating proxy; without it every request looks like HTTP and you get a redirect loop. - Session cookie: the generated
@session_optionsare signed (signing_salt),http_only(the default) andsame_site: "Lax".secureis added automatically when the request is HTTPS, which again depends onrewrite_onbehind a proxy. Setsecure: trueexplicitly if unsure. The cookie is signed, not encrypted: the user can read it. Addencryption_salt:if you store anything they shouldn't see. - WebSockets: keep
check_originenabled (the default) in production. See thephoenix-channels-essentialsskill.
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
- 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 Loggerfirst, and list the metadata keys in the formatter config or they're dropped - Configure log output with
config :logger, :default_formatter(or:default_handlerfor a JSON formatter) —config :logger, :consoleis ignored when:default_formatteris set, which Phoenix 1.8'sconfig.exsdoes - Don't overwrite
request_id—Plug.RequestId(in every generated endpoint) already sets it as Logger metadata; it is not inconn.assigns - Attach handlers once at boot, with
&__MODULE__.handle_event/4and 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 - Use the events Ecto, Phoenix and Oban already emit — don't wrap queries manually; of Ecto's query measurements only
total_timeis always present, so read the others withMap.get/2 - Metric tags must have low cardinality — route, status, queue,
sourceyes;user_id,request_id, email never. Per-user ids belong in log metadata and traces - If the project has its own telemetry wrapper or event catalog, use it instead of calling
:telemetry.execute/3directly - Logger metadata is per process —
Task,GenServerand LiveView processes don't inherit it; pass it on explicitly - LiveDashboard stays inside the generated
dev_routesblock, or behind admin auth — never in a scope with only:browser - Never log at
:debugin production — it includes query parameters (see thedeployment-gotchasskill)
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/metricson port 9568. It doesn't supportsummary; usedistribution(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
- 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 - Test both happy path AND error/invalid cases for every function
- 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 itsaccounts_test.exsand the phx.gen.live / phx.gen.context tests aren't — add it.) - Use the generated fixtures and scopes —
user_fixture/1,user_scope_fixture/0,post_fixture(scope, attrs), andsetup :register_and_log_in_user(putsconn,userandscopein the context). New fixtures go intest/support/fixtures/, never inline across tests - 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 - Assert LiveView structure with
has_element?/3, nothtml =~on markup. When an event navigates, pipe intofollow_redirect/2and assert on the page you land on — the old view is gone - Mock only at boundaries — Mox against a behaviour with
setup :verify_on_exit!; HTTP throughReq.Teststubs. Never mock your own contexts or Repo - Never
Process.sleep/1— useassert_receive,render_async/2,start_supervised!/1 - Test the public context interface, not private helpers or internal state
- Use
describeblocks 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'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'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 ' there.
LiveViewTest helpers worth knowing
| Helper | Use |
|---|---|
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