Phoenix.Endpoint.CowboyAdapter (Phoenix v1.5.13) View Source

The Cowboy adapter for Phoenix.

It implements the required child_spec/3 function as well as the handler for the WebSocket transport.

Custom dispatch options

NOTE: This feature depends on the internals of Cowboy 1.0 API and how it integrates with Phoenix. Those may change at any time, without backwards compatibility.

You can provide custom dispatch options in order to use Phoenix's builtin Cowboy server with custom handlers. For example, to handle raw WebSockets as shown in Cowboy's docs).

The options are passed to both :http and :https keys in the endpoint configuration. However, once you pass your custom dispatch options, you will need to manually wire all Phoenix endpoints, including the socket transports.

You will need the following rules:

  • Per websocket transport:

    {"/socket/websocket", Phoenix.Endpoint.CowboyWebSocket,
      {Phoenix.Transports.WebSocket,
        {MyAppWeb.Endpoint, MyAppWeb.UserSocket, websocket_config}}}
  • Per longpoll transport:

    {"/socket/long_poll", Plug.Adapters.Cowboy.Handler,
      {Phoenix.Transports.LongPoll,
        {MyAppWeb.Endpoint, MyAppWeb.UserSocket, longpoll_config}}}
  • For the live-reload websocket:

    {"/phoenix/live_reload/socket/websocket", Phoenix.Endpoint.CowboyWebSocket,
      {Phoenix.Transports.WebSocket,
        {MyAppWeb.Endpoint, Phoenix.LiveReloader.Socket, websocket_config}}}

    If you decide to include the live-reload websocket, you should disable it when building for production.

  • For the endpoint:

    {:_, Plug.Adapters.Cowboy.Handler, {MyAppWeb.Endpoint, []}}

For example:

config :myapp, MyAppWeb.Endpoint,
  http: [dispatch: [
          {:_, [
              {"/foo", MyAppWeb.CustomHandler, []},
              {"/bar", MyAppWeb.AnotherHandler, []},
              {"/phoenix/live_reload/socket/websocket", Phoenix.Endpoint.CowboyWebSocket,
                {Phoenix.Transports.WebSocket,
                  {MyAppWeb.Endpoint, Phoenix.LiveReloader.Socket, websocket_config}}},
              {:_, Plug.Adapters.Cowboy.Handler, {MyAppWeb.Endpoint, []}}
            ]}]]

Note: if you reconfigure HTTP options in MyAppWeb.Endpoint.init/1, your dispatch options set in mix config will be overwritten.

It is also important to specify your handlers first, otherwise Phoenix will intercept the requests before they get to your handler.