Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1· openaiHugging Face Frontier Reasoning Traces

Build a boilerplate for an Elixir Phoenix web application with LiveView.

  1. User

    Build a boilerplate for an Elixir Phoenix web application with LiveView.

  2. Assistant

    Building Elixir Phoenix Boilerplate

    The user requests a boilerplate for an Elixir Phoenix web application with LiveView. They likely want instructions and a code skeleton. I’m interpreting this as a need for guidance on scaffolding a Phoenix+LiveView app rather than manually generating boilerplate. I should describe how to create a new app using mix phx.new my_app --live and mention the key files and structure. A simple LiveView example, like a counter or todo, would be helpful too!Creating Phoenix Boilerplate Guidance

    Writing an entire Phoenix boilerplate can be overwhelming, so it makes sense to rely on the built-in generator and highlight key modifications. I’ll focus on concise steps and the most relevant parts. First, I’ll assume the user has Elixir and Phoenix installed.

    Step 1 would be to create the project using mix phx.new my_app --live. Step 2 involves showing main components for LiveView, like live sessions in the router and creating a LiveView module. I’ll provide essential snippets, but replicating the entire framework isn't necessary; a minimal approach will work better.Producing Phoenix Boilerplate Guidance

    This is a bit complicated; the recommendation is to use the generator, which aligns with the user's request to "build a boilerplate." I’ll base my approach on the generator while including minimal LiveView rendering. Some users may want a "boilerplate code snippet" for customization, so I can create a template with essentials like mix.exs that lists dependencies such as phoenix and phoenix_live_view. I’ll focus on key modules, like the Router and LiveView layout, while explaining how to scaffold with phx.new --live.Structuring Phoenix Boilerplate

    I realize that even though there could be over 200 lines for each part, the instructions ask for conciseness, so I need to strike a balance. I’ll reorganize my output into clear sections:

    1. Prerequisites
    2. Instructions for generating a new Phoenix + LiveView project
    3. Key files and snippets to treat as boilerplate, including examples
    4. A simple root LiveView like HomeLive with mount and render
    5. A router snippet for hooking the LiveView
    6. The layout for the root HTML.

    Given Phoenix 1.7, I’ll clarify that using the --live flag isn’t necessary since LiveView is now the default.Creating Phoenix Boilerplate with LiveView

    The user wants a Phoenix project that includes LiveView, so I’ll use version 1.7, which has LiveView integrated by default. They can run mix phx.new my_app without needing the --live flag. I'll outline clear steps for them:

    1. Create the project using the necessary commands and ensure all dependencies are checked in mix.exs.
    2. Define the main LiveView in home_live.ex, showing key functionalities like mount and event handling.
    3. Provide a router snippet for connecting the LiveView.
    4. Confirm LiveView socket is set up in endpoint.ex and mention the root layout file.

    This will offer a solid boilerplate example while noting any differences for earlier Phoenix versions. Here’s a minimal but complete way to get a Phoenix + LiveView boilerplate you can actually run and extend.

    I’ll assume Phoenix ≥ 1.7, which ships with LiveView by default.


    1. Generate a new Phoenix project

    If you don’t have the Phoenix generator installed:

    mix archive.install hex phx_new
    

    Then create the project:

    mix phx.new my_app
    cd my_app
    mix ecto.create
    mix phx.server
    

    Visit http://localhost:4000 to verify the project runs.

    On Phoenix < 1.7 you’d typically do:

    mix phx.new my_app --live
    

    Phoenix 1.7 already includes LiveView, so no extra flags are needed.


    2. Check LiveView is in your deps (boilerplate mix.exs)

    Your mix.exs should contain something like:

    defp deps do
      [
        {:phoenix, "~> 1.7.0"},
        {:phoenix_ecto, "~> 4.4"},
        {:ecto_sql, "~> 3.10"},
        {:postgrex, ">= 0.0.0"},
        {:phoenix_html, "~> 4.0"},
        {:phoenix_live_view, "~> 0.20.0"},
        {:floki, ">= 0.30.0", only: :test},
        {:phoenix_live_dashboard, "~> 0.8.0"},
        {:esbuild, "~> 0.8", runtime: Mix.env() == :dev},
        {:telemetry_metrics, "~> 0.6"},
        {:telemetry_poller, "~> 1.0"},
        {:gettext, "~> 0.20"},
        {:jason, "~> 1.4"},
        {:plug_cowboy, "~> 2.6"}
      ]
    end
    

    (Exact versions may differ; the generator fills these in.)

    Install any missing deps:

    mix deps.get
    

    3. Ensure the LiveView socket is wired (boilerplate endpoint.ex)

    Phoenix does this for you, but here’s the key part in lib/my_app_web/endpoint.ex:

    defmodule MyAppWeb.Endpoint do
      use Phoenix.Endpoint, otp_app: :my_app
    
      @session_options [
        store: :cookie,
        key: "_my_app_key",
        signing_salt: "RANDOMSALT"
      ]
    
      socket "/live", Phoenix.LiveView.Socket,
        websocket: [connect_info: [session: @session_options]]
    
      # ...
      plug Plug.Session, @session_options
      plug MyAppWeb.Router
    end
    

    This is the boilerplate wiring that enables LiveView over /live.


    4. Add a LiveView and route (your main boilerplate)

    4.1 Create a LiveView module

    Create lib/my_app_web/live/home_live.ex:

    defmodule MyAppWeb.HomeLive do
      use MyAppWeb, :live_view
    
      @impl true
      def mount(_params, _session, socket) do
        {:ok, assign(socket, count: 0)}
      end
    
      @impl true
      def handle_event("inc", _params, socket) do
        {:noreply, update(socket, :count, &(&1 + 1))}
      end
    
      @impl true
      def handle_event("dec", _params, socket) do
        {:noreply, update(socket, :count, &(&1 - 1))}
      end
    
      @impl true
      def render(assigns) do
        ~H"""
        <.header class="mb-4">
          Welcome to MyApp LiveView
          <:subtitle>A minimal boilerplate counter page.</:subtitle>
        </.header>
    
        <div class="space-y-4">
          <p class="text-xl">
            Current count: <span class="font-mono"><%= @count %></span>
          </p>
    
          <div class="space-x-2">
            <button phx-click="dec"
                    class="px-3 py-1 border rounded">
              -1
            </button>
            <button phx-click="inc"
                    class="px-3 py-1 border rounded">
              +1
            </button>
          </div>
        </div>
        """
      end
    end
    

    This is a clean, generic LiveView you can treat as app boilerplate: state in mount/3, events in handle_event/3, markup in render/1.

    4.2 Wire the route

    Edit lib/my_app_web/router.ex:

    defmodule MyAppWeb.Router do
      use MyAppWeb, :router
    
      pipeline :browser do
        plug :accepts, ["html"]
        plug :fetch_session
        plug :fetch_live_flash
        plug :put_root_layout, {MyAppWeb.Layouts, :root}
        plug :protect_from_forgery
        plug :put_secure_browser_headers
      end
    
      scope "/", MyAppWeb do
        pipe_through :browser
    
        # LiveView homepage boilerplate
        live "/", HomeLive, :index
      end
    
      # You can leave the rest (API scope, etc.) as generated
    end
    

    If the generator already made a PageController and / route, you can replace that get "/" route with the live "/" line above.


    5. Layout boilerplate (root layout + components)

    Phoenix 1.7+ uses components and layout modules. The generator already sets these up; usually you don’t need to touch them for basic boilerplate.

    The default root layout is in lib/my_app_web/components/layouts/root.html.heex, with a structure like:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <%= Phoenix.HTML.Tag.csrf_meta_tag() %>
        <title><%= assigns[:page_title] || "MyApp" %></title>
        <link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
        <script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}></script>
      </head>
      <body class="antialiased">
        <%= @inner_content %>
      </body>
    </html>
    

    The important part for LiveView is the JavaScript hook, which is already included in assets/js/app.js:

    import "phoenix_html"
    import { Socket } from "phoenix"
    import topbar from "../vendor/topbar"
    import { LiveSocket } from "phoenix_live_view"
    
    let csrfToken = document
      .querySelector("meta[name='csrf-token']")
      .getAttribute("content")
    
    let liveSocket = new LiveSocket("/live", Socket, {
      params: { _csrf_token: csrfToken },
    })
    
    // connect if there are any LiveViews on the page
    liveSocket.connect()
    
    // expose for debugging
    window.liveSocket = liveSocket
    

    You generally don’t have to change this for a boilerplate app.


    6. Run the boilerplate

    From the project root:

    mix phx.server
    # or
    iex -S mix phx.server
    

    Visit http://localhost:4000 — you should see your LiveView counter page.


    7. Summary boilerplate pieces

    Core files you now have as a reusable LiveView boilerplate:

    • mix.exs – Phoenix + LiveView deps
    • lib/my_app_web/endpoint.ex – LiveView socket at /live
    • lib/my_app_web/router.ex – live "/", HomeLive, :index
    • lib/my_app_web/live/home_live.ex – starter LiveView module
    • lib/my_app_web/components/layouts/root.html.heex – root HTML shell
    • assets/js/app.js – LiveView JS wiring

    If you’d like, I can expand this into a more opinionated boilerplate (e.g., with auth placeholders, navbar, base components, Tailwind setup) or tailor it to a specific Phoenix version.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.