Skip to content

Request Lifecycle

David Ciulla edited this page Nov 7, 2026 · 1 revision

Request Lifecycle

Introduction

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.


Overview

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

Step 1 — Application Boot

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:

  1. Loads .env via Laravex.Env.load!/1.
  2. Loads config/*.exs via Laravex.Config.Repository.load!/1.
  3. Instantiates the middleware registry (Laravex.Http.Middleware.new/0) and applies any customizations from bootstrap/app.ex.
  4. Resets route and console ETS tables, then calls Routes.Web.register/0 (and optionally Routes.Api, Routes.Auth, Routes.Channels).
  5. Runs register/0 on every provider in Bootstrap.Providers.list/0, then boot/0 on each.
  6. Stores the booted instance in :persistent_term for zero-copy access on every subsequent request.

Step 2 — The Bootstrap File

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
end

This mirrors bootstrap/app.php in Laravel 13 exactly.


Step 3 — Routing

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 404 response (JSON for API/Ajax requests, HTML otherwise).

Step 4 — Middleware Pipeline

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
end

Some 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
end

Global Middleware

Applied 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

Web Group Middleware

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

API Group Middleware

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

Step 5 — Handler Invocation

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).


Step 6 — Response and Session

After the handler returns:

  1. The session is persisted to the configured store (file or database).
  2. The session cookie is set on the response (encrypted if SESSION_ENCRYPT=true).
  3. terminate/2 callbacks run in reverse middleware order.
  4. The final %Laravex.Http.Response{} is serialized back to the HTTP adapter.

Exception Handling

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.


Customizing the Middleware Stack

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.

Clone this wiki locally