Repository navigation
Request Lifecycle
Understanding the full journey of an HTTP request through Laravex helps you know exactly where to hook in middleware, where exceptions are caught, and how the response is assembled. The lifecycle maps closely to Laravel's, adapted for OTP supervision and Elixir conventions.
Incoming HTTP Request
│
▼
Laravex.Http.Server ← Cowboy/inets adapter; builds %Request{}
│
▼
Laravex.Foundation.Application.handle_request/1
│ (boots the application on first request if not already running)
▼
Laravex.Http.Kernel.handle/2
│
├─ Router.match/1 ← match path + method → {handler, opts}
│ returns :error → 404 response
│
├─ Middleware pipeline
│ Global stack (all requests):
│ TrustProxies → TrustHosts → HandleCors
│ → TrimStrings → ConvertEmptyStringsToNull
│ Group stack ("web" or "api"):
│ web: PreventRequestsDuringMaintenance → EncryptCookies
│ → AddQueuedCookies → StartSession → AuthenticateSession
│ → MethodOverride → ShareErrors → ShareFlash
│ → VerifyCsrfToken → SubstituteBindings
│ api: PreventRequestsDuringMaintenance
│ → ThrottleRequests → SubstituteBindings
│
├─ Controller / closure invoked with %Request{}
│
├─ Response assembled (%Response{} | binary body)
│
├─ Session persisted; session cookie set
│
└─ Terminate callbacks (e.g. CORS headers, cache headers)
│
▼
%Laravex.Http.Response{} returned to HTTP adapter
When the BEAM starts, Laravex.Application launches a supervision tree that includes:
children = [
Laravex.Container,
Laravex.Cache.Manager,
Laravex.Queue.Worker,
Laravex.Events.Dispatcher,
Laravex.Broadcasting.Broadcaster,
{Laravex.Foundation.Server, base_path: base_path}
]Laravex.Foundation.Server calls Bootstrap.App.build/1 and then Laravex.Foundation.Application.create/1 during its init/1 callback, which performs the following once at startup:
- Loads
.envviaLaravex.Env.load!/1. - Loads
config/*.exsviaLaravex.Config.Repository.load!/1. - Instantiates the middleware registry (
Laravex.Http.Middleware.new/0) and applies any customizations frombootstrap/app.ex. - Resets route and console ETS tables, then calls
Routes.Web.register/0(and optionallyRoutes.Api,Routes.Auth,Routes.Channels). - Runs
register/0on every provider inBootstrap.Providers.list/0, thenboot/0on each. - Stores the booted instance in
:persistent_termfor zero-copy access on every subsequent request.
bootstrap/app.ex is the single place where you configure the application shape:
defmodule Bootstrap.App do
def build(base_path \\ File.cwd!()) do
Application.configure(base_path: base_path)
|> Application.with_routing(
web: Path.join(base_path, "routes/web.ex"),
commands: Path.join(base_path, "routes/console.ex"),
health: "/up"
)
|> Application.with_middleware(fn middleware ->
middleware
# customize with prepend_to_group / append_to_group / prepend_global
end)
|> Application.with_exceptions(fn exceptions ->
Exceptions.should_render_json_when(exceptions, fn request ->
Request.is?(request, "api/*") or Request.wants_json?(request) or Request.ajax?(request)
end)
end)
end
endThis mirrors bootstrap/app.php in Laravel 13 exactly.
Every incoming request hits Laravex.Http.Kernel.handle/2, which calls Laravex.Routing.Router.match/1. The router scans an ETS table of {method, pattern} → {handler, opts} entries.
- Parameterized segments use
{param}syntax:/users/{id}. - If no route matches, the kernel returns a
404response (JSON for API/Ajax requests, HTML otherwise).
Middleware is run as a sequential pipeline. Each middleware module implements handle/2:
def handle(%Laravex.Http.Request{} = request, opts) do
# inspect / mutate request
{:ok, request} # continue
# or
{:halt, response} # short-circuit; no further middleware or handler runs
endSome middleware also implement terminate/2, called in reverse order after the response is assembled (useful for appending headers without blocking the request):
def terminate(%Laravex.Http.Request{} = request, %Laravex.Http.Response{} = response) do
# mutate response
response
endApplied to every request, before group middleware:
| Module | Responsibility |
|---|---|
TrustProxies |
Honor X-Forwarded-* from trusted proxies |
TrustHosts |
Reject untrusted Host headers |
HandleCors |
CORS headers and OPTIONS preflight |
TrimStrings |
Strip leading/trailing whitespace from input |
ConvertEmptyStringsToNull |
Coerce "" input to nil
|
Applied to routes in the "web" middleware group (the default):
| Module | Responsibility |
|---|---|
PreventRequestsDuringMaintenance |
503 during ./artisan down
|
EncryptCookies |
Decrypt inbound / encrypt outbound cookies |
AddQueuedCookies |
Flush queued cookie/3 calls onto response |
StartSession |
Load or create the session |
AuthenticateSession |
Hydrate request.user from session / remember-me cookie |
MethodOverride |
Honor _method POST spoofing |
ShareErrors |
Merge _errors and _old from session flash |
ShareFlash |
Age flash bag for one request |
VerifyCsrfToken |
Validate CSRF token on mutating requests |
SubstituteBindings |
Resolve {param} segments to Eloquex models |
Applied to routes in the "api" middleware group (added by ./artisan install:api):
| Module | Responsibility |
|---|---|
PreventRequestsDuringMaintenance |
503 during ./artisan down
|
ThrottleRequests |
Rate limiting |
SubstituteBindings |
Resolve route model bindings |
After the pipeline completes with {:ok, request}, the kernel invokes the matched handler:
# Closure route
Router.get("/", fn request -> View.make("welcome") end)
# Controller route
Router.get("/users/{id}", {App.Http.Controllers.UserController, :show})The handler receives the fully enriched %Laravex.Http.Request{} struct and must return either a %Laravex.Http.Response{} or a binary string (which is wrapped in an HTML response automatically).
After the handler returns:
- The session is persisted to the configured store (
fileordatabase). - The session cookie is set on the response (encrypted if
SESSION_ENCRYPT=true). -
terminate/2callbacks run in reverse middleware order. - The final
%Laravex.Http.Response{}is serialized back to the HTTP adapter.
Any exception raised during routing or the handler is caught by Laravex.Foundation.Application.handle_request/1 and delegated to Laravex.Foundation.Exceptions.render/3. The renderer inspects the request (using the should_render_json_when callback from bootstrap/app.ex) to decide between a JSON error payload and an HTML error page.
Validation failures (Laravex.Validation.Failed) are handled with the same mechanism, typically returning a 422 response or redirect with flashed errors.
Modify the middleware configuration in bootstrap/app.ex using the fluent builder API:
|> Application.with_middleware(fn middleware ->
middleware
|> Laravex.Http.Middleware.append_to_group("web", MyApp.Middleware.Locale)
|> Laravex.Http.Middleware.prepend_to_group("api", MyApp.Middleware.ApiVersion)
|> Laravex.Http.Middleware.prepend_global(MyApp.Middleware.RequestId)
end)See Middleware for the full middleware API and all built-in aliases.
Laravex — Laravel-faithful application skeleton & runtime for Elixir.
GitHub
·
Docs
·
Limitations
·
Laravel Docs
Not affiliated with Laravel LLC or the Elixir core team. Built to feel like Laravel on the BEAM.
- Home
- Installation
- Configuration
- Directory-Structure
- Request-Lifecycle
- Service-Container
- Service-Providers
- Deployment
- Routing
- Middleware
- CSRF-Protection
- Controllers
- Requests
- Responses
- Views
- Blade-Templates
- Asset-Bundling
- Session
- Validation
- Error-Handling
- Logging
- Artisan-Console
- Broadcasting
- Cache
- Collections
- Events
- File-Storage
- Helpers
- HTTP-Client
- Localization
- Notifications
- Pipeline
- Queues
- Rate-Limiting
- Strings
- Task-Scheduling