phoenix-routing
Define routes and URL helpers in Phoenix applications including resources, scopes, pipelines, and verified routes
What this skill does
# Phoenix Routing
Phoenix routing maps incoming HTTP requests to controller actions. The router is the entry point for all web requests and determines which controller action should handle each request. Phoenix provides powerful routing macros for RESTful resources, scopes, pipelines, and verified routes.
## Basic Route Declaration
### Single Routes
Define individual routes using HTTP verb macros:
```elixir
get "/", PageController, :home
```
Phoenix supports all standard HTTP verbs:
```elixir
get "/users", UserController, :index
post "/users", UserController, :create
patch "/users/:id", UserController, :update
put "/users/:id", UserController, :update
delete "/users/:id", UserController, :delete
```
### Routes with Dynamic Segments
Capture URL parameters using the `:param_name` syntax:
```elixir
get "/hello/:messenger", HelloController, :show
```
The `:messenger` segment becomes available in the controller's params map.
## Resource Routes
### Basic Resource Declaration
Generate all standard RESTful routes with the `resources` macro:
```elixir
resources "/users", UserController
```
This generates eight routes:
```text
GET /users UserController :index
GET /users/:id/edit UserController :edit
GET /users/new UserController :new
GET /users/:id UserController :show
POST /users UserController :create
PATCH /users/:id UserController :update
PUT /users/:id UserController :update
DELETE /users/:id UserController :delete
```
### Limiting Resource Routes
Use `:only` to generate specific routes:
```elixir
resources "/users", UserController, only: [:show]
resources "/posts", PostController, only: [:index, :show]
```
Use `:except` to exclude specific routes:
```elixir
resources "/users", UserController, except: [:create, :delete]
```
### Aliasing Resources
Customize the route path helper name with `:as`:
```elixir
resources "/users", UserController, as: :person
```
This generates path helpers like `~p"/person"` instead of `~p"/users"`.
### Nested Resources
Create hierarchical resource relationships:
```elixir
resources "/users", UserController do
resources "/posts", PostController
end
```
Generated routes include the parent resource ID:
```text
GET /users/:user_id/posts PostController :index
GET /users/:user_id/posts/:id/edit PostController :edit
GET /users/:user_id/posts/new PostController :new
GET /users/:user_id/posts/:id PostController :show
POST /users/:user_id/posts PostController :create
PATCH /users/:user_id/posts/:id PostController :update
PUT /users/:user_id/posts/:id PostController :update
DELETE /users/:user_id/posts/:id PostController :delete
```
## Verified Routes
### Using the ~p Sigil
Phoenix provides compile-time verified routes using the `~p` sigil:
```elixir
# Static paths
~p"/users"
~p"/posts/new"
# Dynamic segments with variables
~p"/users/#{user_id}"
~p"/users/#{user_id}/posts/#{post_id}"
```
### Verified Routes with Structs
Pass structs directly to generate paths:
```elixir
~p"/users/#{@user}"
# Generates: "/users/42"
~p"/users/#{user}/posts/#{post}"
# Generates: "/users/42/posts/17"
```
Phoenix automatically extracts the ID using the `Phoenix.Param` protocol.
### Benefits of Verified Routes
1. **Compile-time validation** - Catch routing errors during compilation
2. **Refactoring safety** - Route changes are caught immediately
3. **Type safety** - Ensure correct parameter types
4. **URL slug support** - Easy transition to slug-based URLs
## Scopes
### Basic Scopes
Group routes under a common path prefix:
```elixir
scope "/admin", HelloWeb.Admin do
pipe_through :browser
resources "/users", UserController
end
```
Generated paths include the scope prefix:
```elixir
~p"/admin/users"
```
### Scopes with Aliases
Reduce repetition by aliasing controller modules:
```elixir
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :home
resources "/posts", PostController
end
```
### Nested Scopes
Create hierarchical route organization:
```elixir
scope "/api", HelloWeb.Api, as: :api do
pipe_through :api
scope "/v1", V1, as: :v1 do
resources "/users", UserController
end
scope "/v2", V2, as: :v2 do
resources "/users", UserController
end
end
```
Generated path helpers reflect the nesting:
```elixir
~p"/api/v1/users"
~p"/api/v2/users"
```
## Pipelines
### Defining Pipelines
Pipelines group plugs that run for specific routes:
```elixir
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {HelloWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
```
### Applying Pipelines to Scopes
Use `pipe_through` to apply pipelines:
```elixir
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :home
resources "/users", UserController
end
scope "/api", HelloWeb.Api do
pipe_through :api
resources "/users", UserController
end
```
### Custom Plugs in Pipelines
Add application-specific plugs:
```elixir
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {HelloWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug HelloWeb.Plugs.Locale, "en"
end
```
### Nesting Pipelines
Compose pipelines for complex authentication flows:
```elixir
pipeline :auth do
plug :browser
plug :ensure_authenticated_user
plug :ensure_user_owns_review
end
scope "/reviews", HelloWeb do
pipe_through :auth
resources "/", ReviewController
end
```
This applies the `:browser` pipeline first, then the authentication plugs.
## Advanced Pipeline Patterns
### Session Management Pipeline
Create a pipeline for session-based features:
```elixir
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {HelloWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :fetch_current_scope_for_user
end
defp fetch_current_scope_for_user(conn, _opts) do
if id = get_session(conn, :scope_id) do
assign(conn, :current_scope, MyApp.Scope.for_id(id))
else
id = System.unique_integer()
conn
|> put_session(:scope_id, id)
|> assign(:current_scope, MyApp.Scope.for_id(id))
end
end
```
### Multi-tenant Routing
Assign organization context from URL parameters:
```elixir
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {HelloWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :fetch_current_scope_for_user
plug :assign_org_to_scope
end
defp assign_org_to_scope(conn, _opts) do
case conn.params["org"] do
nil -> conn
org_slug ->
scope = conn.assigns.current_scope
org = MyApp.Organizations.get_by_slug!(org_slug)
assign(conn, :current_scope, Map.put(scope, :organization, org))
end
end
```
### Shopping Cart Pipeline
Fetch or create a cart for the current session:
```elixir
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {HelloWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :fetch_current_scope_for_user
plug :fetch_current_cart
end
alias MyApp.ShoppingCart
defp fetch_current_cart(%{assigns: %{current_scope: scope}} = conn, _opts)
when not is_nil(scope) do
if cart = ShoppingCart.get_cart(scope) do
assign(conn, :cart, cart)
else
{:ok, new_cart} = ShoppingCart.create_cart(scope, %{})
assign(conn, :cart, new_cart)
end
end
defp fetch_current_cart(conn, _opts), do: conn
```
## Forwarding
### Forward to Plugs
Delegate a path prefix to another plug or appliRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.