Skip to content

Middleware

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

Middleware

Middleware in Laravex works identically to Laravel: each piece of middleware inspects or transforms the request before it reaches the route handler, and may also modify the response on the way back out. The middleware stack is defined in Laravex.Http.Middleware and configured in bootstrap/app.ex.

Middleware Structure

Every middleware module exposes a handle/2 callback:

def handle(request, opts) do
  # Inspect or modify the request ...
  {:ok, request}         # continue the pipeline
  # or
  {:halt, response}      # short-circuit and return this response
end

Middleware that also needs to touch the response implements terminate/2:

def terminate(request, response) do
  # Modify response (e.g. add headers, encrypt cookies) ...
  response
end

terminate/2 is called in reverse middleware order, mirroring Laravel's "after" middleware pattern.

Global Middleware

The global stack runs on every request, before group middleware. The default stack is:

Module Purpose
TrustProxies Honour X-Forwarded-* headers from trusted proxies
TrustHosts Reject requests with an untrusted Host header
HandleCors CORS headers and OPTIONS preflight
TrimStrings Strip leading/trailing whitespace from string inputs
ConvertEmptyStringsToNull Convert "" input values to nil

Middleware Groups

web

Applied to routes that use the "web" middleware group (the default):

Module Purpose
PreventRequestsDuringMaintenance Return 503 during maintenance mode
EncryptCookies Decrypt inbound / encrypt outbound cookies when session.encrypt is true
AddQueuedCookies Attach cookies queued via CookieJar
StartSession Load (or create) the session from the cookie
AuthenticateSession Hydrate request.user from the session or remember-me cookie
MethodOverride Honour _method spoofing on POST requests
ShareErrors Share _errors / _old from the session onto the request
ShareFlash Age the flash bag for the current request
VerifyCsrfToken Verify the CSRF token for state-changing requests
SubstituteBindings Resolve {param} route parameters to Eloquex models

api

Applied to routes that use the "api" middleware group:

Module Purpose
PreventRequestsDuringMaintenance Return 503 during maintenance mode
ThrottleRequests (limiter: "api") Rate-limit by IP against the named "api" limiter
SubstituteBindings Resolve route parameter model bindings

Middleware Aliases

Aliases let you apply middleware by a short string key in route definitions. The following aliases are built-in and resolved by Laravex.Http.Middleware.resolve_alias/1:

Alias Module Notes
auth Authenticate Redirect to /login or return 401 JSON
auth:api Authenticate Force JSON 401 (skips redirect)
guest RedirectIfAuthenticated Redirect authenticated users away
can:ability Authorize Check a gate ability
can:ability,resource Authorize Check ability against a route-bound model
throttle ThrottleRequests 60 req/min default
throttle:30,1 ThrottleRequests 30 req/min
throttle:api ThrottleRequests Named rate-limiter
signed ValidateSignature Require a valid signed URL
cache.headers:public;max_age=60;etag SetCacheHeaders Set Cache-Control / ETag headers
ability:posts:read CheckTokenAbility Require a single token ability
abilities:read,write CheckTokenAbility Require all listed token abilities

Apply aliases via the :middleware option:

Router.get("/dashboard", {DashboardController, :index}, middleware: ["auth"])

Router.group([middleware: ["auth", "can:manage-posts"]], fn ->
  Router.resource("posts", PostController)
end)

Router.get("/webhooks", {WebhookController, :store}, middleware: ["throttle:100,1"])

Configuring Middleware in bootstrap/app.ex

The Application.with_middleware/2 callback receives the Laravex.Http.Middleware struct and returns a modified copy. Use it to append or prepend middleware to any group:

Application.with_middleware(fn middleware ->
  middleware
  |> Laravex.Http.Middleware.append_to_group("web", App.Http.Middleware.VerifyEmail)
  |> Laravex.Http.Middleware.prepend_global(App.Http.Middleware.LogRequests)
end)

Available functions:

Function Description
append_global/2 Append to the global stack
prepend_global/2 Prepend to the global stack
append_to_group/3 Append to a named group ("web" or "api")
prepend_to_group/3 Prepend to a named group

TrustProxies

Configure trusted proxies via the TRUSTED_PROXIES environment variable or config("app.trusted_proxies"). Accepts * (all), a comma-separated list of IPs, or CIDR blocks:

TRUSTED_PROXIES=10.0.0.0/8,192.168.1.1

When a request arrives from a trusted proxy, X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Host are honoured and stored in the process dictionary so that Request.ip/1 and Request.secure?/1 reflect the real client values.

TrustHosts

Configure trusted hostnames via TRUSTED_HOSTS or config("app.trusted_hosts"). Supports leading *. subdomain wildcards:

TRUSTED_HOSTS=example.com,*.example.com

An empty/nil list disables host validation.

CORS

CORS is handled by HandleCors. Configure it in config/cors.exs:

%{
  "paths"               => ["api/*"],
  "allowed_origins"     => ["*"],
  "allowed_methods"     => ["*"],
  "allowed_headers"     => ["*"],
  "exposed_headers"     => [],
  "max_age"             => 0,
  "supports_credentials"=> false
}

TrimStrings

TrimStrings whitespace-strips all string params except password, password_confirmation, and current_password. Add extra exclusions by passing :except when registering a custom middleware instance.

Writing Custom Middleware

defmodule App.Http.Middleware.EnsureEmailVerified do
  def handle(request, _opts) do
    user = request.user

    if is_nil(user) or Map.get(user, :email_verified_at) do
      {:ok, request}
    else
      {:halt, Laravex.Http.Response.redirect("/email/verify")}
    end
  end
end

Register it in bootstrap/app.ex:

Application.with_middleware(fn middleware ->
  Laravex.Http.Middleware.append_to_group(middleware, "web", App.Http.Middleware.EnsureEmailVerified)
end)

Or apply it to individual routes by module atom or alias string:

Router.get("/settings", {SettingsController, :index},
  middleware: [App.Http.Middleware.EnsureEmailVerified])

Clone this wiki locally