Phoenix.Router

Defines a Phoenix router.

The router provides a set of macros for generating routes that dispatch to specific controllers and actions. Those macros are named after HTTP verbs. For example:

defmodule MyApp.Router do
  use Phoenix.Router

  get "/pages/:page", PageController, :show
end

The get/3 macro above accepts a request of format “/pages/VALUE” and dispatches it to the show action in the PageController.

Routes can also match glob-like patterns, routing any path with a common base to the same controller. For example:

get "/dynamic*anything", DynamicController, :show

Phoenix’s router is extremely efficient, as it relies on Elixir pattern matching for matching routes and serving requests.

Helpers

Phoenix automatically generates a module Helpers inside your router which contains named helpers to help developers generate and keep their routes up to date.

Helpers are automatically generated based on the controller name. For example, the route:

get "/pages/:page", PageController, :show

will generate the following named helper:

MyApp.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
"/pages/hello"

MyApp.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
"/pages/hello?some=query"

MyApp.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
"http://example.com/pages/hello?some=query"

MyApp.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
"http://example.com/pages/hello?some=query"

The url generated in the named url helpers is based on the configuration for :url, :http and :https.

The named helper can also be customized with the :as option. Given the route:

get "/pages/:page", PageController, :show, as: :special_page

the named helper will be:

MyApp.Router.Helpers.special_page_path(conn, :show, "hello")
"/pages/hello"

Scopes and Resources

The router also supports scoping of routes:

scope "/api/v1", as: :api_v1 do
  get "/pages/:id", PageController, :show
end

For example, the route above will match on the path `”/api/v1/pages/:id” and the named route will be api_v1_page_path, as expected from the values given to scope/2 option.

Phoenix also provides a resources/4 macro that allows developers to generate “RESTful” routes to a given resource:

defmodule MyApp.Router do
  use Phoenix.Router

  resources "/pages", PageController, only: [:show]
  resources "/users", UserController, except: [:delete]
end

Finally, Phoenix ships with a mix phoenix.routes task that nicely formats all routes in a given router. We can use it to verify all routes included in the router above:

$ mix phoenix.routes
page_path  GET    /pages/:id       PageController.show/2
user_path  GET    /users           UserController.index/2
user_path  GET    /users/:id/edit  UserController.edit/2
user_path  GET    /users/new       UserController.new/2
user_path  GET    /users/:id       UserController.show/2
user_path  POST   /users           UserController.create/2
user_path  PATCH  /users/:id       UserController.update/2
           PUT    /users/:id       UserController.update/2

One can also pass a router explicitly as an argument to the task:

$ mix phoenix.routes MyApp.Router

Check scope/2 and resources/4 for more information.

Pipelines and plugs

Once a request arrives at the Phoenix router, it performs a series of transformations through pipelines until the request is dispatched to a desired end-point.

Such transformations are defined via plugs, as defined in the Plug specification. Once a pipeline is defined, it can be piped through per scope.

For example:

defmodule MyApp.Router do
  use Phoenix.Router

  pipeline :browser do
    plug :fetch_session
    plug :accepts, ["html"]
  end

  scope "/" do
    pipe_through :browser

    # browser related routes and resources
  end
end

Phoenix.Router imports functions from both Plug.Conn and Phoenix.Controller to help define plugs. In the example above, fetch_session/2 comes from Plug.Conn while accepts/2 comes from Phoenix.Controller.

Note that router pipelines are only invoked after a route is found. No plug is invoked in case no matches were found.

Channels

Channels allow you to route pubsub events to channel handlers in your application. By default, Phoenix supports both WebSocket and LongPoller transports. See the Phoenix.Channel.Transport documentation for more information on writing your own transports. Channels are defined with a socket mount, ie:

defmodule MyApp.Router do
  use Phoenix.Router

  socket "/ws" do
    channel "rooms:*", MyApp.RoomChannel
  end
end
Source

Summary

channel(topic_pattern, module, opts \\ [])

Defines a channel matching the given topic and transports

connect(path, controller, action, options \\ [])

Generates a route to handle a connect request to the given path

delete(path, controller, action, options \\ [])

Generates a route to handle a delete request to the given path

get(path, controller, action, options \\ [])

Generates a route to handle a get request to the given path

head(path, controller, action, options \\ [])

Generates a route to handle a head request to the given path

options(path, controller, action, options \\ [])

Generates a route to handle a options request to the given path

patch(path, controller, action, options \\ [])

Generates a route to handle a patch request to the given path

pipe_through(pipes)

Defines a pipeline to send the connection through

pipeline(plug, list2)

Defines a plug pipeline

plug(plug, opts \\ [])

Defines a plug inside a pipeline

post(path, controller, action, options \\ [])

Generates a route to handle a post request to the given path

put(path, controller, action, options \\ [])

Generates a route to handle a put request to the given path

resource(path, controller)

See resource/4

resource(path, controller, opts)

See resource/4

resource(path, controller, opts, list4)

Defines “RESTful” routes for a resource that client’s lookup without referencing an ID

resources(path, controller)

See resources/4

resources(path, controller, opts)

See resources/4

resources(path, controller, opts, list4)

Defines “RESTful” routes for a resource

scope(options, list2)

Defines a scope in which routes can be nested

scope(path, options, list3)

Define a scope with the given path

scope(path, alias, options, list4)

Defines a scope with the given path and alias

socket(mount, list2)

Defines a socket mount-point for channel definitions

socket(mount, opts, list3)
socket(mount, chan_alias, opts, list4)
trace(path, controller, action, options \\ [])

Generates a route to handle a trace request to the given path

Macros

channel(topic_pattern, module, opts \\ [])

Defines a channel matching the given topic and transports.

  • topic_pattern - The string pattern, ie “rooms:“, “users:“, “system”
  • module - The channel module handler, ie MyApp.RoomChannel
  • opts - The optional list of options, see below

Options

  • :via - the transport adapters to accept on this channel. Defaults [Phoenix.Transports.WebSocket, Phoenix.Transports.LongPoller]

Examples

socket "/ws" do
  channel "topic1:*", MyChannel
  channel "topic2:*", MyChannel, via: [Phoenix.Transports.WebSocket]
  channel "topic",    MyChannel, via: [Phoenix.Transports.LongPoller]
end

Topic Patterns

The channel macro accepts topic patterns in two flavors. A splat argument can be provided as the last character to indicate a “topic:subtopic” match. If a plain string is provied, only that topic will match the channel handler. Most use-cases will use the “topic:*” pattern to allow more versatile topic scoping.

See Phoenix.Channel for more information

Source
connect(path, controller, action, options \\ [])

Generates a route to handle a connect request to the given path.

Source
delete(path, controller, action, options \\ [])

Generates a route to handle a delete request to the given path.

Source
get(path, controller, action, options \\ [])

Generates a route to handle a get request to the given path.

Source
head(path, controller, action, options \\ [])

Generates a route to handle a head request to the given path.

Source
options(path, controller, action, options \\ [])

Generates a route to handle a options request to the given path.

Source
patch(path, controller, action, options \\ [])

Generates a route to handle a patch request to the given path.

Source
pipe_through(pipes)

Defines a pipeline to send the connection through.

See pipeline/2 for more information.

Source
pipeline(plug, list2)

Defines a plug pipeline.

Pipelines are defined at the router root and can be used from any scope.

Examples

pipeline :api do
  plug :token_authentication
  plug :dispatch
end

A scope may then use this pipeline as:

scope "/" do
  pipe_through :api
end

Every time pipe_through/1 is called, the new pipelines are appended to the ones previously given.

Source
plug(plug, opts \\ [])

Defines a plug inside a pipeline.

See pipeline/2 for more information.

Source
post(path, controller, action, options \\ [])

Generates a route to handle a post request to the given path.

Source
put(path, controller, action, options \\ [])

Generates a route to handle a put request to the given path.

Source
resource(path, controller)

See resource/4.

Source
resource(path, controller, opts)

See resource/4.

Source
resource(path, controller, opts, list4)

Defines “RESTful” routes for a resource that client’s lookup without referencing an ID.

The given definition:

resource "/account", UserController

will include routes to the following actions:

  • GET /account => :show
  • GET /account/new => :new
  • POST /account => :create
  • GET /account/edit => :edit
  • PATCH /account => :update
  • PUT /account => :update
  • DELETE /account => :delete

Options

This macro accepts the same options as resources/4

Source
resources(path, controller)

See resources/4.

Source
resources(path, controller, opts)

See resources/4.

Source
resources(path, controller, opts, list4)

Defines “RESTful” routes for a resource.

The given definition:

resources "/users", UserController

will include routes to the following actions:

  • GET /users => :index
  • GET /users/new => :new
  • POST /users => :create
  • GET /users/:id => :show
  • GET /users/:id/edit => :edit
  • PATCH /users/:id => :update
  • PUT /users/:id => :update
  • DELETE /users/:id => :delete

Options

This macro accepts a set of options:

  • :only - a list of actions to generate routes for, for example: [:show, :edit]
  • :except - a list of actions to exclude generated routes from, for example: [:delete]
  • :param - the name of the paramter for this resource, defaults to "id"
  • :name - the prefix for this resource. This is used for the named helper and as the prefix for the parameter in nested resources. The default value is automatically derived from the controller name, i.e. UserController will have name "user"
  • :as - configures the named helper exclusively
Source
scope(options, list2)

Defines a scope in which routes can be nested.

Examples

scope “/api/v1”, as: :api_v1, alias: API.V1 do

get "/pages/:id", PageController, :show

end

The generated route above will match on the path `”/api/v1/pages/:id” and will dispatch to :show action in API.V1.PageController. A named helper api_v1_page_path will also be generated.

Options

The supported options are:

  • :path - a string containing the path scope
  • :as - a string or atom containing the named helper scope
  • :alias - an alias (atom) containing the controller scope
  • :host - a string containing the host scope, or prefix host scope, ie

    `"foo.bar.com"`, `"foo."`
  • :private - a map of private data to merge into the connection when a route matches
Source
scope(path, options, list3)

Define a scope with the given path.

This function is a shortcut for:

scope path: path do
  ...
end
Source
scope(path, alias, options, list4)

Defines a scope with the given path and alias.

This function is a shortcut for:

scope path: path, alias: alias do
  ...
end
Source
socket(mount, list2)

Defines a socket mount-point for channel definitions.

By default, the given path is a websocket upgrade endpoint, with long-polling fallback. The transports can be configured with the socket options or on each individual channel.

It expects the mount path as a string and a keyword list of options.

Options

  • :via - the optional transport modules to apply to all channels in the block, ie: [Phoenix.Transports.WebSocket]

  • :as - the optional named route helper function, ie :socket

  • :alias - the optional alias to apply to all channel modules, ie: MyApp. Alternatively, you can pass an alias as a standalone second argument to apply the alias, similar to scope/2.

Examples

socket "/ws" do
  channel "rooms:*", MyApp.RoomChannel
end

socket "/ws", MyApp do
  channel "rooms:*", RoomChannel
end

socket "/ws", alias: MyApp, as: :socket, via: [Phoenix.Transports.WebSocket] do
  channel "rooms:*", RoomChannel
end
Source
socket(mount, opts, list3)
Source
socket(mount, chan_alias, opts, list4)
Source
trace(path, controller, action, options \\ [])

Generates a route to handle a trace request to the given path.

Source