Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Routing, Controllers and Plugs

Plugs in Depth: Function and Module Plugs

Understand Plug, the specification behind Phoenix: write function plugs and module plugs with init/1 and call/2, assign data, halt requests and test plugs.

Almost everything in Phoenix is a plug: the endpoint, the router, the session parser, even controllers. Plug is a small specification: a plug is either a function (conn, opts) -> conn or a module with init/1 and call/2. Once you can write plugs, you can add logging, authentication, rate limiting, locale detection and more in a few lines.

This lesson shows both kinds of plug, how options flow in at compile time, how to halt a request and how to test a plug without a browser. You met pipelines in router and pipelines.

The conn

%Plug.Conn{} holds the request fields (method, request_path, params, req_headers, host, remote_ip) and the response fields you build (status, resp_headers, resp_body), plus assigns for your own data and halted, a flag. You never mutate it: every helper returns a new conn.

ELIXIR
import Plug.Conn

conn
|> put_resp_header("x-app", "blog")
|> assign(:current_user, user)
|> put_status(200)

Function plugs

The simplest plug is a function of arity 2 in your router or controller:

ELIXIR
defp put_locale(conn, _opts) do
  locale =
    case get_req_header(conn, "accept-language") do
      ["de" <> _ | _] -> "de"
      _ -> "en"
    end

  Gettext.put_locale(BlogWeb.Gettext, locale)
  assign(conn, :locale, locale)
end

Use it with plug :put_locale in a pipeline. In a controller, plug :authorize when action in [:edit, :update, :delete] runs a plug only for some actions.

Module plugs

For reuse, write a module. init/1 runs once at compile time (or boot) and prepares options; call/2 runs on every request with those prepared options.

ELIXIR
defmodule BlogWeb.Plugs.RequireRole do
  import Plug.Conn
  import Phoenix.Controller

  def init(opts), do: Keyword.fetch!(opts, :role)

  def call(conn, role) do
    user = conn.assigns[:current_user]

    if user && user.role == role do
      conn
    else
      conn
      |> put_flash(:error, "Not allowed.")
      |> redirect(to: "/")
      |> halt()
    end
  end
end

Use it as plug BlogWeb.Plugs.RequireRole, role: :admin. Because init/1 runs once, put expensive work such as compiling a regex there, not in call/2.

Halting

If a plug sends a response (a redirect, a 401, a JSON error), it must call halt/1. Without it, the pipeline continues and a later plug or the controller tries to send a second response, raising Plug.Conn.AlreadySentError. A common mistake is forgetting halt() after redirect.

ELIXIR
def call(conn, _opts) do
  case get_req_header(conn, "x-api-key") do
    [key] when key != "" -> assign(conn, :api_key, key)
    _ -> conn |> send_resp(401, "missing key") |> halt()
  end
end

Ordering and the endpoint

The endpoint (lib/blog_web/endpoint.ex) lists plugs that run for every request before the router, in a fixed order that matters:

ELIXIR
plug Plug.Static, at: "/", from: :blog, gzip: false, only: BlogWeb.static_paths()
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug BlogWeb.Router

Static files are served first so that image requests skip everything else. The body parsers must come before anything that reads conn.params. Moving a plug can change behavior, so add your own after the parsers and before the router unless you have a reason not to.

A rate-limiting plug, in Elixir

ELIXIR
defmodule BlogWeb.Plugs.RateLimit do
  import Plug.Conn

  def init(opts), do: %{limit: Keyword.get(opts, :limit, 60)}

  def call(conn, %{limit: limit}) do
    key = {:rate, conn.remote_ip, div(System.system_time(:second), 60)}
    count = :ets.update_counter(:rate_limits, key, 1, {key, 0})

    if count > limit do
      conn |> put_resp_header("retry-after", "60") |> send_resp(429, "slow down") |> halt()
    else
      conn
    end
  end
end

It uses an ETS table (see ETS and Registry) to count requests per IP per minute. The ETS table would be created when the app starts.

Testing a plug

Plugs are plain functions, so tests are short. Plug.Test builds a conn without HTTP:

ELIXIR
import Plug.Test

test "rejects a missing api key" do
  conn = conn(:get, "/") |> BlogWeb.Plugs.ApiKey.call([])
  assert conn.halted
  assert conn.status == 401
end

You will test controllers and plugs together in Testing and Deployment.

Plugs, modeled

JS init once, call many times

Press Run (or Ctrl + Enter) to see the console output here.

No output.

init ran one time inside plugModule; the returned function reuses the prepared option on each call, which is what Phoenix does at compile time.

JS Rate limiter plug

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The seventh request is blocked, but a request a minute later starts a new bucket, matching the div(time, 60) trick in the Elixir version.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a plug do after sending a response, such as a redirect?

    halt/1 marks the conn halted so later plugs and the controller do not run or send a second response.
  2. 2. When does init/1 of a module plug run?

    init/1 prepares options once; call/2 receives them for each request.
  3. 3. Why does Plug.Static come first in the endpoint?

    Early plugs can answer and halt, which makes static file requests cheap.
  4. 4. What is a valid plug?

    Plugs are functions of arity 2 or modules implementing init/1 and call/2.

Summary

  • A plug is (conn, opts) -> conn; function plugs are local, module plugs implement init/1 and call/2.
  • init/1 runs once; call/2 runs per request.
  • Always halt/1 after sending a response inside a plug.
  • Plug order in the endpoint and pipelines changes behavior; test plugs with Plug.Test.

Next: Resources and verified routes