Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Routing, Controllers and Plugs

Router, Scopes and Pipelines

Learn how the Phoenix router maps requests to controllers, groups routes with scope, applies plugs with pipelines and how route matching order works.

The router is the map of your application. It lists every URL your app responds to and says which code handles it. Phoenix compiles the router into fast pattern-matching functions, so a lookup takes microseconds even with hundreds of routes.

In this lesson you will write routes for each HTTP verb, group them with scope, apply plugs with pipeline and pipe_through, and learn why the order of routes matters. Everything builds on the request lifecycle.

Phoenix code is read-only on this site. The JavaScript TryIts model route matching and pipelines so you can try the ideas.

Defining routes

Open lib/blog_web/router.ex. A route has a verb macro, a path, a controller and an action name (an atom):

ELIXIR
scope "/", BlogWeb do
  pipe_through :browser

  get "/", PageController, :home
  get "/about", PageController, :about
  get "/posts", PostController, :index
  get "/posts/:id", PostController, :show
  post "/posts", PostController, :create
  put "/posts/:id", PostController, :update
  patch "/posts/:id", PostController, :update
  delete "/posts/:id", PostController, :delete
end

The verb macros are get, post, put, patch, delete, options and head. A segment starting with : is a dynamic segment: /posts/42 produces the params %{"id" => "42"}. A trailing * captures the rest of the path as a list:

ELIXIR
get "/files/*path", FileController, :show
# /files/img/logo.png  =>  %{"path" => ["img", "logo.png"]}

Browsers can only send GET and POST from forms. Phoenix's Plug.MethodOverride reads a hidden _method field, so a form can submit PUT or DELETE. The generated form helpers add that field for you.

Scopes

scope groups routes under a common path prefix, controller module namespace and, optionally, an alias for helper names:

ELIXIR
scope "/admin", BlogWeb.Admin, as: :admin do
  pipe_through [:browser, :require_admin]

  get "/", DashboardController, :index
  get "/posts", PostController, :index
end

Here get "/posts" maps to /admin/posts and the controller is BlogWeb.Admin.PostController. Scopes can nest, which is useful for versioned APIs such as scope "/api" containing scope "/v1".

Pipelines

A pipeline is a named list of plugs. Routes opt in with pipe_through:

ELIXIR
pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_live_flash
  plug :put_root_layout, html: {BlogWeb.Layouts, :root}
  plug :protect_from_forgery
  plug :put_secure_browser_headers
end

pipeline :api do
  plug :accepts, ["json"]
end

The :browser pipeline prepares everything an HTML page needs: session, flash messages, CSRF protection and security headers. The :api pipeline only negotiates JSON. Keeping them separate means API requests never pay for sessions.

You can write your own function plugs in the router module and use them in a pipeline, for example plug :put_locale. A pipeline's plugs run in order, and a plug can halt the request (for instance, redirecting to the login page).

flowchart LR
  A["Request"] --> B["Endpoint plugs"]
  B --> C{"Router match"}
  C -->|"/posts"| D[":browser pipeline"]
  C -->|"/api/posts"| E[":api pipeline"]
  D --> F["Controller"]
  E --> F

Order matters

The router tries routes top to bottom and takes the first match. This causes a classic bug:

ELIXIR
get "/posts/:id", PostController, :show
get "/posts/new", PostController, :new    # never reached!

/posts/new matches :id first, with id = "new". Put the specific route above the dynamic one. The resources macro, covered in resources and verified routes, orders them correctly for you.

If nothing matches, Phoenix raises Phoenix.Router.NoRouteError, which becomes a 404 page. In dev it shows the list of known routes.

Forwarding and mounting

forward hands a path prefix to another plug or router, handy for mounting a separate Plug app or a library:

ELIXIR
forward "/health", BlogWeb.HealthPlug

LiveView routes use live, and the dashboard uses live_dashboard, both macros that expand to routes behind the scenes.

Route matching, modeled

JS A router with dynamic segments

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

No output.

Move the :id route above /posts/new in the code and run it again: /posts/new now returns { id: "new" }, the bug from above.

Pipelines, modeled

JS pipe_through with halting

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

No output.

The second call stops at requireUser, the same way a Phoenix plug calls halt/1 after redirecting.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a pipeline do?

    A pipeline groups plugs, and scopes or routes opt in with pipe_through.
  2. 2. Given get "/posts/:id" listed before get "/posts/new", what happens for /posts/new?

    Routes are tried top to bottom, so the dynamic route wins. Put specific routes first.
  3. 3. What does scope "/admin", BlogWeb.Admin do?

    A scope sets a path prefix and a controller namespace; protection needs plugs in a pipeline.
  4. 4. Why do browsers need Plug.MethodOverride for PUT and DELETE?

    HTML forms only submit GET or POST, so a hidden _method field tells Phoenix the intended verb.

Summary

  • Routes pair an HTTP verb and path with a controller action; :name captures a segment and *rest captures the remainder.
  • scope adds a prefix, a module namespace and shared pipelines.
  • Pipelines (:browser, :api) are ordered plugs applied with pipe_through.
  • The first matching route wins, so define specific routes before dynamic ones.

Next: Controllers and params