Claude
Skills
Sign in
Back

phoenix-routing

Included with Lifetime
$97 forever

Define routes and URL helpers in Phoenix applications including resources, scopes, pipelines, and verified routes

General

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 appli

Related in General