Elixir Phoenix & LiveView Overview
Phoenix is Elixir's main web framework. It handles HTTP requests, JSON APIs, WebSockets (channels) and real-time server-rendered UIs with LiveView. Phoenix applications are known for low latency and for handling huge numbers of simultaneous connections, because every request and every live connection is just a lightweight BEAM process.
This lesson is an overview: Phoenix needs a Mix project and Hex packages, so its code is shown in non-run blocks. The runnable examples model the core ideas in plain Elixir.
Creating an app
$ mix archive.install hex phx_new
$ mix phx.new shop # includes Ecto (PostgreSQL) and LiveView
$ cd shop
$ mix ecto.create
$ mix phx.server # http://localhost:4000The main pieces:
| Piece | Role |
|---|---|
| Endpoint | the entry point: receives connections, applies common plugs |
| Router | maps paths and HTTP verbs to controllers or LiveViews |
| Plug | a function that takes a connection and returns a (modified) connection |
| Controller | handles a request and renders HTML or JSON |
| Contexts | plain modules with your business logic (Shop.Catalog, Shop.Accounts) |
| Ecto | database layer: schemas, changesets, queries, migrations |
| LiveView | stateful, real-time UI rendered on the server |
| PubSub / Channels | broadcast messages between processes and to browsers |
Plug: the request pipeline
At its heart, Phoenix is a pipeline of functions over a connection struct (%Plug.Conn{}): each plug reads it and returns an updated one, or halts the pipeline. The same idea in plain Elixir, with a map standing in for the conn:
defmodule MiniPlug do
def log(conn), do: Map.update!(conn, :log, &["#{conn.method} #{conn.path}" | &1])
def authenticate(%{headers: %{"authorization" => "Bearer secret"}} = conn),
do: Map.put(conn, :user, "admin")
def authenticate(conn), do: conn |> Map.put(:status, 401) |> Map.put(:body, "unauthorized") |> Map.put(:halted, true)
def route(%{halted: true} = conn), do: conn
def route(%{method: "GET", path: "/products"} = conn), do: %{conn | status: 200, body: ~s([{"id":1,"name":"Lamp"}])}
def route(conn), do: %{conn | status: 404, body: "not found"}
def call(conn), do: conn |> log() |> authenticate() |> route()
def new(method, path, headers \\ %{}),
do: %{method: method, path: path, headers: headers, status: nil, body: nil, halted: false, log: []}
end
for conn <- [
MiniPlug.new("GET", "/products", %{"authorization" => "Bearer secret"}),
MiniPlug.new("GET", "/products"),
MiniPlug.new("GET", "/nope", %{"authorization" => "Bearer secret"})
] do
result = MiniPlug.call(conn)
IO.puts("#{conn.method} #{conn.path} -> #{result.status} #{result.body}")
endGET /products -> 200 [{"id":1,"name":"Lamp"}]
GET /products -> 401 unauthorized
GET /nope -> 404 not found
In real Phoenix, the router groups plugs into pipelines and sends requests to controllers:
# lib/shop_web/router.ex
pipeline :api do
plug :accepts, ["json"]
plug ShopWeb.Auth
end
scope "/api", ShopWeb do
pipe_through :api
get "/products", ProductController, :index
post "/products", ProductController, :create
end
# lib/shop_web/controllers/product_controller.ex
defmodule ShopWeb.ProductController do
use ShopWeb, :controller
def index(conn, _params) do
json(conn, Shop.Catalog.list_products())
end
endEcto in one glance
defmodule Shop.Catalog.Product do
use Ecto.Schema
import Ecto.Changeset
schema "products" do
field :name, :string
field :price, :decimal
timestamps()
end
def changeset(product, attrs) do
product
|> cast(attrs, [:name, :price])
|> validate_required([:name, :price])
|> validate_number(:price, greater_than: 0)
end
end
# A query
import Ecto.Query
Repo.all(from p in Product, where: p.price < 20, order_by: p.name, select: p.name)A changeset collects casting and validation. Invalid data never reaches the database, and the errors are shown in the form.
LiveView: state on the server
A LiveView is a process per browser tab. It holds the page state (assigns), renders HTML from it, and receives events (clicks, form changes) over a WebSocket. After each event it re-renders and sends only the changed parts to the browser. No JavaScript to write for most interactions.
defmodule ShopWeb.CounterLive do
use ShopWeb, :live_view
def mount(_params, _session, socket), do: {:ok, assign(socket, count: 0)}
def handle_event("inc", _params, socket), do: {:noreply, update(socket, :count, &(&1 + 1))}
def render(assigns) do
~H"""
<p>Clicked {@count} times</p>
<button phx-click="inc">+1</button>
"""
end
endThe model behind it is a loop of mount → render → event → update state → render. Here it is simulated with plain functions:
defmodule TodoLive do
def mount, do: %{todos: [], filter: :all}
def handle_event("add", %{"title" => t}, state), do: %{state | todos: state.todos ++ [%{title: t, done: false}]}
def handle_event("toggle", %{"index" => i}, state), do: %{state | todos: List.update_at(state.todos, i, &%{&1 | done: !&1.done})}
def handle_event("filter", %{"by" => by}, state), do: %{state | filter: String.to_existing_atom(by)}
def render(state) do
visible = Enum.filter(state.todos, fn t -> state.filter == :all or (state.filter == :open and not t.done) end)
lines = Enum.map(visible, fn t -> " [#{if t.done, do: "x", else: " "}] #{t.title}" end)
Enum.join(["<ul> (#{state.filter})" | lines], "\n")
end
end
events = [
{"add", %{"title" => "Write lesson"}},
{"add", %{"title" => "Review PR"}},
{"toggle", %{"index" => 0}},
{"filter", %{"by" => "open"}}
]
state = TodoLive.mount()
Enum.reduce(events, state, fn {event, params}, state ->
new_state = TodoLive.handle_event(event, params, state)
IO.puts("after #{event}:\n" <> TodoLive.render(new_state))
new_state
end)after add:
<ul> (all)
[ ] Write lesson
after add:
<ul> (all)
[ ] Write lesson
[ ] Review PR
after toggle:
<ul> (all)
[x] Write lesson
[ ] Review PR
after filter:
<ul> (open)
[ ] Review PR
String.to_existing_atom/1 is used because event parameters come from the browser: creating atoms from user input could fill the atom table, which is never garbage collected.
Real-time with PubSub
Phoenix.PubSub.broadcast(Shop.PubSub, "orders", {:new_order, order}) sends a message to every process subscribed to the "orders" topic. A LiveView that subscribed in mount/3 receives it in handle_info/2 and updates the page of every connected user at once. It is the same message passing you learned in the Processes lesson, distributed across a cluster if needed.
Where to go next
- The official Phoenix guides (hexdocs.pm/phoenix) and
mix phx.gen.live/mix phx.gen.jsongenerators. - Programming Phoenix LiveView and the Ecto documentation.
- Livebook for interactive notebooks with Elixir.
Test yourself
What is a Plug?
- A database adapter
- A function (or module) that takes a connection and returns a connection
- A JavaScript library
- A LiveView template
Where does a LiveView keep its state?
- In browser localStorage
- In a server-side process, in the socket's assigns
- In the database only
- In a cookie
What does an Ecto changeset do?
- Opens a database connection
- Casts and validates data before it is inserted or updated
- Defines routes
- Renders HTML