Pass options to a specific plug in a plug pipeline

Hey, is there a way to pass options to a specific plug in Plug.Builder?
For example:

defmodule PlugPipeline do
  use Plug.Builder 

  plug(:plug1)
  plug(:plug2)

  plug(:my_plug)

  def my_plug(conn, opts) do
    10 = Keyword.get(opts, :my_plug_option)
    conn
  end
end

Then (in test for example):

PlugPipeline.call(conn, my_plug_option: 10)

Do you mean like this?

plug :my_plug, my_plug_option: 10

The thing is that this is static and I would like to pass options dynamically when calling call/2 on the pipeline, but passing opts for a specific plug.

I believe you cannot pass options directly to individual plugs at runtime, as this behavior is by design. Plug pipelines and their constituent plugs are defined and configured at compile time.

I’m not entirely sure what you’re trying to achieve, but if your goal is to test behavior, you should consider testing each plug individually.

If you really need to pass runtime data to individual plugs in a pipeline, you might consider using conn.assigns for that purpose. Here’s an example:

defmodule PlugPipeline do
  use Plug.Builder

  plug(:my_plug)

  def my_plug(conn, _opts) do
    10 = Keyword.get(conn.assigns.opts, :my_plug_option)
    conn
  end

  def call(conn, opts) do
    conn |> Plug.Conn.assign(:opts, opts) |> super(opts)
  end
end

Yep, this should do the job. For testing purposes I use :init_mode option which inits plugs at runtime, hence thought should be doable. Thanks!

1 Like