Analyzing Requirements
I'm currently dissecting the user's need for an Elixir Phoenix LiveView boilerplate. I'm identifying essential elements beyond the standard mix phx.new output. Things like common dependencies and structural elements are coming into focus. I need to figure out what extra configurations would represent "best practices".
Expanding the Scope
I've broadened the scope to include essential libraries, offer directory structure explanations, and consider Docker for deployment. I'm aiming for a reference for developers wanting to quickly bootstrap new projects with a strong foundation in Elixir and Phoenix. I'm focusing on the core components for a robust boilerplate, starting with current Elixir/Phoenix versions (1.14+, 1.7+), PostgreSQL, Tailwind CSS, phx.gen.auth for authentication, and Swoosh for mail. Testing will rely on ExUnit defaults, and I'll include Credo and Dialyxir for linting/formatting and a basic Docker setup for deployment.
Building the Blueprint
I'm now focusing on a concrete, step-by-step approach for creating the boilerplate. First, I'm documenting the base command: mix phx.new my_app --binary-id --database postgres. Next, I'll integrate mix phx.gen.auth Accounts User for authentication. Beyond the essentials, I decided to include credo and dialyxir in mix.exs to ensure good code quality, and I'm adding floki to meet requirements for testing LiveView components.
Detailing the Steps
I'm solidifying the steps now. Besides the core setup, I need to integrate Alpine.js. Also, I must highlight the essential importance of Dockerization for contemporary deployments. I'm also considering the final output structure, including an introduction, prerequisites, core setup commands, mix.exs adjustments, Alpine.js integration, tooling configurations, Docker usage, and a summary.
Refining Implementation
I'm now focusing on actionable steps. It's crucial to explain why each code snippet exists, not just provide the code. I'm double-checking the app.js import syntax for Phoenix 1.7+. The Alpine.js integration is central. I'll include instructions for ESBuild-based imports in app.js since Phoenix 1.7+ handles imports nicely. To finish this, I need to make the output copy-paste friendly and think about useful aliases.
Revising Scope
I'm making a key adjustment: removing Oban from the core boilerplate, moving it to "recommended additions." Keeping the starting point simple is my priority. This change refines the boilerplate's focus, keeping it more general-purpose and avoiding unnecessary complexity.
This boilerplate assumes you want a production-ready base using modern best practices: Phoenix 1.7+, LiveView, Tailwind CSS, PostgreSQL, and standard Code Quality tools.
Here is a step-by-step guide to building a robust boilerplate.
1. Initialization
Run the generator with specific flags to set up UUIDs (better for replication/syncing) and standard dependencies.
# Install the latest Phx archive
mix archive.install hex phx_new
# Generate the app
# --binary-id: Use UUIDs instead of Integers for IDs
# --database postgres: Explicitly set DB
# --no-mailer: We will add Swoosh manually if needed,
# but usually standard generation includes it.
mix phx.new my_app --binary-id --database postgres
cd my_app
2. Add Authentication
Don't roll your own authentication. Use the standard, secure generator provided by Phoenix.
mix phx.gen.auth Accounts User
- Select
y to fetch dependencies and run migrations.
3. Essential Dependencies (mix.exs)
Open mix.exs and add tools for code quality and static analysis. These are standard in professional Elixir shops.
defp deps do
[
# ... existing deps ...
{:phoenix_live_view, "~> 0.20.1"}, # Ensure you are on the latest
# standard: Tooling
{:credo, "~> 1.7", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false},
{:sobelow, "~> 0.13", only: [:dev, :test], runtime: false}, # Security checks
]
end
Run mix deps.get.
4. Client-Side Interactivity (Alpine.js)
While LiveView handles 90% of interactions, Alpine.js is the standard for handling client-side only UI (dropdowns, modals) to avoid unnecessary server round-trips.
-
Install Alpine inside assets:
cd assets
npm install alpinejs
-
Configure assets/js/app.js:
import "phoenix_html"
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import Alpine from "alpinejs" // <--- Import Alpine
window.Alpine = Alpine // <--- Optional: makes Alpine accessible in console
Alpine.start() // <--- Start Alpine
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
// Add this to bridge Alpine and LiveView:
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to)
}
}
}
})
// ... rest of file
5. Quality of Life Aliases
Add a composite alias to run all code quality checks in one command. In mix.exs, inside defp aliases do:
defp aliases do
[
setup: ["deps.get", "ecto.setup", "assets.setup", "assets.build"],
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"],
"assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"],
"assets.build": ["tailwind default", "esbuild default"],
"assets.deploy": ["tailwind default --minify", "esbuild default --minify", "phx.digest"],
# Add this:
quality: [
"format --check-formatted",
"credo --strict",
"dialyzer",
"sobelow --config"
]
]
end
Now you can run mix quality in CI/CD or locally to ensure code standards.
6. Configuration Configs
Strict Credo (.credo.exs)
Generate a config to enforce style:
mix credo.gen.config
Dialyzer Setup
In mix.exs inside project do:
def project do
[
# ...
dialyzer: [
plt_add_apps: [:ex_unit],
plt_file: {:no_warn, "priv/plts/dialyzer.plt"}
]
]
end
(Make sure to add priv/plts/ to your .gitignore)
7. Production Ready Dockerfile
Phoenix now has a generator for releases which creates a Dockerfile for you.
mix phx.gen.release --docker
This creates a generic Dockerfile, .dockerignore, and rel/overlays/bin/migrate script. This setup utilizes Elixir Releases, making the resulting container extremely small (Alpine Linux based) and it doesn't require Erlang/Elixir on the host machine to run.
8. Base Layout (Standardizing Tailwind)
Update lib/my_app_web/components/layouts/app.html.heex to include a basic container structure so you aren't fighting CSS immediately.
<header class="px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between border-b border-zinc-100 py-3 text-sm">
<div class="flex items-center gap-4">
<a href="/">
<img src={~p"/images/logo.svg"} width="36" />
</a>
</div>
<div class="flex items-center gap-4 font-semibold leading-6 text-zinc-900">
<%= if @current_user do %>
<span class="text-zinc-500"><%= @current_user.email %></span>
<.link href={~p"/users/settings"} class="hover:text-zinc-700">Settings</.link>
<.link href={~p"/users/log_out"} method="delete" class="hover:text-zinc-700">Log out</.link>
<% else %>
<.link href={~p"/users/register"} class="hover:text-zinc-700">Register</.link>
<.link href={~p"/users/log_in"} class="hover:text-zinc-700">Log in</.link>
<% end %>
</div>
</div>
</header>
<main class="px-4 py-20 sm:px-6 lg:px-8">
<div class="mx-auto max-w-2xl">
<.flash_group flash={@flash} />
<%= @inner_content %>
</div>
</main>
Summary of Commands to Run the Boilerplate
mix setup (Installs deps, creates DB, migrates).
mix test (Ensures everything is green).
mix quality (Checks code style).
mix phx.server (Starts the app).
Recommended Next Steps (Libraries to consider)
For a reasonably complex app, you will almost certainly need these eventually:
- Oban: For background jobs (emails, report generation).
- Floki: For HTML parsing (used in testing LiveViews).
- Req: The modern, friendly HTTP client for Elixir.
- Faker: For generating realistic data in
priv/repo/seeds.exs.