Phoenix v1.4.9 Phoenix.Endpoint behaviour View Source
Defines a Phoenix endpoint.
The endpoint is the boundary where all requests to your web application start. It is also the interface your application provides to the underlying web servers.
Overall, an endpoint has three responsibilities:
to provide a wrapper for starting and stopping the endpoint as part of a supervision tree
to define an initial plug pipeline for requests to pass through
to host web specific configuration for your application
Endpoints
An endpoint is simply a module defined with the help
of Phoenix.Endpoint
. If you have used the mix phx.new
generator, an endpoint was automatically generated as
part of your application:
defmodule YourApp.Endpoint do
use Phoenix.Endpoint, otp_app: :your_app
# plug ...
# plug ...
plug YourApp.Router
end
Endpoints must be explicitly started as part of your application supervision tree. Endpoints are added by default to the supervision tree in generated applications. Endpoints can be added to the supervision tree as follows:
children = [
YourApp.Endpoint
]
Endpoint configuration
All endpoints are configured in your application environment. For example:
config :your_app, YourApp.Endpoint,
secret_key_base: "kjoy3o1zeidquwy1398juxzldjlksahdk3"
Endpoint configuration is split into two categories. Compile-time configuration means the configuration is read during compilation and changing it at runtime has no effect. The compile-time configuration is mostly related to error handling.
Runtime configuration, instead, is accessed during or
after your application is started and can be read through the
config/2
function:
YourApp.Endpoint.config(:port)
YourApp.Endpoint.config(:some_config, :default_value)
Dynamic configuration
For dynamically configuring the endpoint, such as loading data
from environment variables or configuration files, Phoenix invokes
the init/2
callback on the endpoint, passing a :supervisor
atom as first argument and the endpoint configuration as second.
All of Phoenix configuration, except the Compile-time configuration
below can be set dynamically from the init/2
callback.
Compile-time configuration
:code_reloader
- whentrue
, enables code reloading functionality. For code the list of code reloader configuration options seePhoenix.CodeReloader.reload!/1
:debug_errors
- whentrue
, usesPlug.Debugger
functionality for debugging failures in the application. Recommended to be set totrue
only in development as it allows listing of the application source code during debugging. Defaults tofalse
:render_errors
- responsible for rendering templates whenever there is a failure in the application. For example, if the application crashes with a 500 error during a HTML request,render("500.html", assigns)
will be called in the view given to:render_errors
. Defaults to:[view: MyApp.ErrorView, accepts: ~w(html), layout: false]
The default format is used when none is set in the connection
Runtime configuration
:cache_static_manifest
- a path to a json manifest file that contains static files and their digested version. This is typically set to "priv/static/cache_manifest.json" which is the file automatically generated bymix phx.digest
:check_origin
- configure transports to checkorigin
header or not. May befalse
,true
, a list of hosts that are allowed, or a function provided as MFA tuple. Hosts also support wildcards.For example, using a list of hosts:
check_origin: ["//phoenixframework.org", "//*.example.com"]
or a custom MFA function:
check_origin: {MyAppWeb.Auth, :my_check_origin?, []}
The MFA is invoked with the request
%URI{}
as the first argument, followed by arguments in the MFA listDefaults to
true
.:http
- the configuration for the HTTP server. Currently uses Cowboy and accepts all options as defined byPlug.Cowboy
. Defaults tofalse
:https
- the configuration for the HTTPS server. Currently uses Cowboy and accepts all options as defined byPlug.Cowboy
. Defaults tofalse
:force_ssl
- ensures no data is ever sent via HTTP, always redirecting to HTTPS. It expects a list of options which are forwarded toPlug.SSL
. By default it sets the "strict-transport-security" header in HTTPS requests, forcing browsers to always use HTTPS. If an unsafe request (HTTP) is sent, it redirects to the HTTPS version using the:host
specified in the:url
configuration. To dynamically redirect to thehost
of the current request, set:host
in the:force_ssl
configuration tonil
:secret_key_base
- a secret key used as a base to generate secrets for encrypting and signing data. For example, cookies and tokens are signed by default, but they may also be encrypted if desired. Defaults tonil
as it must be set per application:server
- whentrue
, starts the web server when the endpoint supervision tree starts. Defaults tofalse
. Themix phx.server
task automatically sets this totrue
:url
- configuration for generating URLs throughout the app. Accepts the:host
,:scheme
,:path
and:port
options. All keys except:path
can be changed at runtime. Defaults to:[host: "localhost", path: "/"]
The
:port
option requires either an integer, string, or{:system, "ENV_VAR"}
. When given a tuple like{:system, "PORT"}
, the port will be referenced fromSystem.get_env("PORT")
at runtime as a workaround for releases where environment specific information is loaded only at compile-time.The
:host
option requires a string or{:system, "ENV_VAR"}
. Similar to:port
, when given a tuple like{:system, "HOST"}
, the host will be referenced fromSystem.get_env("HOST")
at runtime.The
:scheme
option accepts"http"
and"https"
values. Default value is infered from top level:http
or:https
option. It is useful when hosting Phoenix behind a load balancer or reverse proxy and terminating SSL there.The
:path
option can be used to override root path. Useful when hosting Phoenix behind a reverse proxy with URL rewrite rules:static_url
- configuration for generating URLs for static files. It will fallback tourl
if no option is provided. Accepts the same options asurl
:watchers
- a set of watchers to run alongside your server. It expects a list of tuples containing the executable and its arguments. Watchers are guaranteed to run in the application directory, but only when the server is enabled. For example, the watcher below will run the "watch" mode of the webpack build tool when the server starts. You can configure it to whatever build tool or command you want:[node: ["node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin"]]
The
:cd
option can be used on a watcher to override the folder from which the watcher will run. By default this will be the project's root:File.cwd!()
[node: ["node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin"], cd: "my_frontend"]
:live_reload
- configuration for the live reload option. Configuration requires a:patterns
option which should be a list of file patterns to watch. When these files change, it will trigger a reload. If you are using a tool like pow in development, you may need to set the:url
option appropriately.live_reload: [ url: "ws://localhost:4000", patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif)$}, ~r{web/views/.*(ex)$}, ~r{web/templates/.*(eex)$} ] ]
:pubsub
- configuration for this endpoint's pubsub adapter. Configuration either requires a:name
of the registered pubsub server or a:name
and:adapter
pair. The pubsub name and adapter are compile time configuration, while the remaining options are runtime. The given adapter and name pair will be started as part of the supervision tree. If no adapter is specified, the pubsub system will work by sending events and subscribing to the given name. Defaults to:[adapter: Phoenix.PubSub.PG2, name: MyApp.PubSub]
It also supports custom adapter configuration:
[name: :my_pubsub, adapter: Phoenix.PubSub.Redis, host: "192.168.100.1"]
Endpoint API
In the previous section, we have used the config/2
function that is
automatically generated in your endpoint. Here's a list of all the functions
that are automatically defined in your endpoint:
- for handling paths and URLs:
struct_url/0
,url/0
,path/1
,static_url/0
,static_path/1
, andstatic_integrity/1
- for handling channel subscriptions:
subscribe/2
andunsubscribe/1
- for broadcasting to channels:
broadcast/3
,broadcast!/3
,broadcast_from/4
, andbroadcast_from!/4
- for configuration:
start_link/0
,config/2
, andconfig_change/2
- as required by the
Plug
behaviour:Plug.init/1
andPlug.call/2
Instrumentation
Phoenix uses the :telemetry
library for instrumentation. The following events
are published by Phoenix with the following measurements and metadata:
[:phoenix, :endpoint, :start]
- dispatched byPlug.Telemetry
in your endpoint at the beginning of every request.- Measurement:
%{time: System.monotonic_time}
- Metadata:
%{conn: Plug.Conn.t}
- Measurement:
[:phoenix, :endpoint, :stop]
- dispatched byPlug.Telemetry
in your endpoint whenever the response is sent- Measurement:
%{duration: native_time}
- Metadata:
%{conn: Plug.Conn.t}
- Measurement:
[:phoenix, :router_dispatch, :start]
- dispatched byPhoenix.Router
before dispatching to a matched route- Measurement:
%{time: System.monotonic_time}
- Metadata:
%{conn: Plug.Conn.t, route: binary, plug: module, plug_opts: term, path_params: map, pipe_through: [atom]}
- Measurement:
[:phoenix, :router_dispatch, :stop]
- dispatched byPhoenix.Router
after successfully dispatching to a matched route- Measurement:
%{duration: native_time}
- Metadata:
%{conn: Plug.Conn.t, route: binary, plug: module, plug_opts: term, path_params: map, pipe_through: [atom]}
- Measurement:
[:phoenix, :error_rendered]
- dispatched at the end of an error view being rendered- Measurement:
%{duration: native_time}
- Metadata:
%{status: Plug.Conn.status, kind: Exception.kind, reason: term, stacktrace: Exception.stacktrace}
- Measurement:
[:phoenix, :socket_connected]
- dispatched at the end of a socket connection- Measurement:
%{duration: native_time}
- Metadata:
%{endpoint: atom, transport: atom, params: term, connect_info: map, vsn: binary, user_socket: atom, result: :ok | :error, serializer: atom}
- Measurement:
[:phoenix, :channel_joined]
- dispatched at the end of a channel join- Measurement:
%{duration: native_time}
- Metadata:
%{params: term, socket: Phoenix.Socket.t}
- Measurement:
[:phoenix, :channel_handled_in]
- dispatched at the end of a channel handle in- Measurement:
%{duration: native_time}
- Metadata:
%{event: binary, params: term, socket: Phoenix.Socket.t}
- Measurement:
Link to this section Summary
Functions
Checks if Endpoint's web server has been configured to start.
Defines a websocket/longpoll mount-point for a socket.
Callbacks
Broadcasts a msg
as event
in the given topic
.
Broadcasts a msg
as event
in the given topic
.
Broadcasts a msg
from the given from
as event
in the given topic
.
Broadcasts a msg
from the given from
as event
in the given topic
.
Access the endpoint configuration given by key.
Reload the endpoint configuration on application upgrades.
Initialize the endpoint configuration.
Generates the path information when routing to this endpoint.
Starts the endpoint supervision tree.
Generates an integrity hash to a static file in priv/static
.
Generates a two item tuple containing the static_path
and static_integrity
.
Generates a route to a static file in priv/static
.
Generates the static URL without any path information.
Generates the endpoint base URL, but as a URI
struct.
Subscribes the caller to the given topic.
Unsubscribes the caller from the given topic.
Generates the endpoint base URL without any path information.
Link to this section Types
event()
View Source
event() :: String.t()
event() :: String.t()
msg()
View Source
msg() :: map()
msg() :: map()
topic()
View Source
topic() :: String.t()
topic() :: String.t()
Link to this section Functions
server?(otp_app, endpoint) View Source
Checks if Endpoint's web server has been configured to start.
otp_app
- The OTP app running the endpoint, for example:my_app
endpoint
- The endpoint module, for exampleMyApp.Endpoint
Examples
iex> Phoenix.Endpoint.server?(:my_app, MyApp.Endpoint)
true
socket(path, module, opts \\ []) View Source (macro)
Defines a websocket/longpoll mount-point for a socket.
Note: for backwards compatibility purposes, the :websocket
and :longpoll
options only have an effect if the socket
given as argument has no transport
declarations in it.
Options
:websocket
- controls the websocket configuration. Defaults totrue
. May be false or a keyword list of options. See "Shared configuration" and "WebSocket configuration" for the whole list:longpoll
- controls the longpoll configuration. Defaults tofalse
. May be true or a keyword list of options. See "Shared configuration" and "Longpoll configuration" for the whole list:shutdown
- the maximum shutdown time of each channel when the endpoint is shutting down. Applies only to channel-based sockets
Examples
socket "/ws", MyApp.UserSocket
socket "/ws/admin", MyApp.AdminUserSocket,
longpoll: true,
websocket: [compress: true]
Path params
It is possible to include variables in the path, these will be
available in the params
that are passed to the socket.
socket "/ws/:user_id", MyApp.UserSocket,
websocket: [path: "/project/:project_id"]
Note: This feature is not supported with the Cowboy 1 adapter.
Shared configuration
The configuration below can be given to both :websocket
and
:longpoll
keys:
:path
- the path to use for the transport. Will default to the transport name ("/websocket" or "/longpoll"):serializer
- a list of serializers for messages. SeePhoenix.Socket
for more information:transport_log
- if the transport layer itself should log and, if so, the level:check_origin
- if we should check the origin of requests when the origin header is present. It defaults to true and, in such cases, it will check against the host value inYourApp.Endpoint.config(:url)[:host]
. It may be set tofalse
(not recommended) or to a list of explicitly allowed origins.check_origin: ["https://example.com", "//another.com:888", "//other.com"]
Note: To connect from a native app be sure to either have the native app set an origin or allow any origin via
check_origin: false
:code_reloader
- enable or disable the code reloader. Defaults to your endpoint configuration:connect_info
- a list of keys that represent data to be copied from the transport to be made available in the user socketconnect/3
callbackThe valid keys are:
:peer_data
- the result ofPlug.Conn.get_peer_data/1
:x_headers
- all request headers that have an "x-" prefix:uri
- a%URI{}
with information from the conn{:session, session_config}
- the session information fromPlug.Conn
. Thesession_config
is an exact copy of the arguments given toPlug.Session
. This requires the "_csrf_token" to be given as request parameter with the value ofURI.encode_www_form(Plug.CSRFProtection.get_csrf_token())
when connecting to the socket. Otherwise the session will benil
.
Arbitrary keywords may also appear following the above valid keys, which is useful for passing custom connection information to the socket.
For example:
socket "/socket", AppWeb.UserSocket, websocket: [ connect_info: [:peer_data, :x_headers, :uri, session: [store: :cookie]] ]
With arbitrary keywords:
socket "/socket", AppWeb.UserSocket, websocket: [ connect_info: [:uri, custom_value: "abcdef"] ]
Websocket configuration
The following configuration applies only to :websocket
.
:timeout
- the timeout for keeping websocket connections open after it last received data, defaults to 60_000ms:max_frame_size
- the maximum allowed frame size in bytes. Supported from Cowboy 2.3 onwards, defaults to "infinity":compress
- whether to enable per message compresssion on all data frames, defaults to false
Longpoll configuration
The following configuration applies only to :longpoll
:
:window_ms
- how long the client can wait for new messages in its poll request:pubsub_timeout_ms
- how long a request can wait for the pubsub layer to respond:crypto
- options for verifying and signing the token, accepted byPhoenix.Token
. By default tokens are valid for 2 weeks
Link to this section Callbacks
broadcast(topic, event, msg) View Source
Broadcasts a msg
as event
in the given topic
.
broadcast!(topic, event, msg) View Source
Broadcasts a msg
as event
in the given topic
.
Raises in case of failures.
broadcast_from(from, topic, event, msg) View Source
Broadcasts a msg
from the given from
as event
in the given topic
.
broadcast_from!(from, topic, event, msg) View Source
Broadcasts a msg
from the given from
as event
in the given topic
.
Raises in case of failures.
config(key, default) View Source
Access the endpoint configuration given by key.
config_change(changed, removed) View Source
Reload the endpoint configuration on application upgrades.
init(atom, config) View Source
Initialize the endpoint configuration.
Invoked when the endpoint supervisor starts, allows dynamically configuring the endpoint from system environment or other runtime sources.
path(path) View Source
Generates the path information when routing to this endpoint.
start_link()
View Source
start_link() :: Supervisor.on_start()
start_link() :: Supervisor.on_start()
Starts the endpoint supervision tree.
Starts endpoint's configuration cache and possibly the servers for handling requests.
static_integrity(path) View Source
Generates an integrity hash to a static file in priv/static
.
static_lookup(path) View Source
Generates a two item tuple containing the static_path
and static_integrity
.
static_path(path) View Source
Generates a route to a static file in priv/static
.
static_url()
View Source
static_url() :: String.t()
static_url() :: String.t()
Generates the static URL without any path information.
struct_url()
View Source
struct_url() :: URI.t()
struct_url() :: URI.t()
Generates the endpoint base URL, but as a URI
struct.
subscribe(topic, opts) View Source
Subscribes the caller to the given topic.
See Phoenix.PubSub.subscribe/3
for options.
unsubscribe(topic) View Source
Unsubscribes the caller from the given topic.
url()
View Source
url() :: String.t()
url() :: String.t()
Generates the endpoint base URL without any path information.