Integrate CorsPlug into a Phoenix application
mainWhen using Phoenix, placing CORSPlug in a standard pipeline may not work because pipelines are only invoked for matched routes.
There are two recommended integration patterns:
- Endpoint Level (Recommended): Add the plug directly to your
Endpointmodule so it intercepts all requests before they reach the router. - Router/Pipeline Level: Add
CORSPlugto a specific pipeline and ensure you defineoptionsroutes for your resources to handle preflight requests.
Note: Options passed directly to the plug override application configuration, which in turn overrides default options.
# Pattern 1: Endpoint Level
defmodule YourApp.Endpoint do
use Phoenix.Endpoint, otp_app: :your_app
# ...
plug CORSPlug
plug YourApp.Router
end
# Pattern 2: Router Pipeline Level
pipeline :api do
plug CORSPlug
# ...
end
scope "/api", PhoenixApp do
pipe_through :api
resources "/articles", ArticleController
options "/articles", ArticleController, :options
options "/articles/:id", ArticleController, :options
end