Trying to grok plugs. Why does forward work while pipe_through doesn't in router.ex?

I’m trying to better understand the relationship between a Phoenix router and a Plug.
I’ve generated the base Phoenix app, created a Plug, Phoenixsimple.HelloPlug.

When I add this line:
forward “/hello”, Phoenixsimple.HelloPlug
to the bottom of the router, localhost:4000/hello runs through the plug which does the following and displays “Hello world” on the web page:
def call(conn, _opts) do
conn
|> put_resp_content_type(“text/plain”)
|> send_resp(200, “Hello world”)
end

But, when instead I eliminate the forward and add a pipleline near the top of the router code:
pipeline :myhello do
plug Phoenixsimple.HelloPlug
end

Then do the following, after scope “/”:

scope “/hello”, PhoenixsimpleWeb do
pipe_through :myhello
end

When I hit localhost:4000/hello I get “No route found for GET /hello”
Is there no way to use pipe_through? Must I use forward? Why?
Thanks in advance for bettering our understanding of routes and plugs.
Cheer!

Pipelines are only run if the router does match something in the scope. Scopes alone (as per their naming) are only meant for grouping, but do not match on their own.

The example generated code puts the following in the router.ex. It sounds the following would never get routed?

other scopes may use custom stacks.
#scope “/api”, PhoenixsimpleWeb do
#pipe_through :api
#end

If that’s the case then what must I add to
scope “/hello”, PhoenixsimpleWeb do
pipe_through :myhello
end

to get the router to route the request to the pipeline?
pipeline :myhello do
plug Phoenixsimple.HelloPlug
end

Or am I stuck with using forward?

Thanks for your quick response.

This is actually commented out because it’s not yet doing anything useful. You might want to take a look at the guides here, which includes all the info you should need.
https://hexdocs.pm/phoenix/routing.html#content

2 Likes