Repository navigation
Session
Laravex provides a Laravel-compatible session layer implemented in Laravex.Session.Store. Sessions are identified by a cookie, stored in a request-local ETS cache for the duration of a request, and persisted to a durable backend at the end of every response.
Session configuration lives in config/session.exs (or via environment variables). The key options:
| Config key | Env var | Default | Description |
|---|---|---|---|
session.driver |
SESSION_DRIVER |
"file" |
Storage backend: "file", "database", or "redis"
|
session.lifetime |
SESSION_LIFETIME |
120 |
Session TTL in minutes |
session.cookie |
SESSION_COOKIE |
"laravex-session" |
Cookie name |
session.path |
— | "/" |
Cookie path |
session.domain |
SESSION_DOMAIN |
nil |
Cookie domain |
session.secure |
SESSION_SECURE_COOKIE |
false |
Require HTTPS |
session.http_only |
— | true |
HttpOnly flag |
session.same_site |
— | "lax" |
SameSite policy |
session.encrypt |
— | false |
Encrypt the session ID in the cookie |
session.lottery |
— | [2, 100] |
GC lottery odds [hits, total]
|
session.files |
— | storage/framework/sessions |
File driver storage path |
Sessions are serialised with :erlang.term_to_binary/1 and written as individual files under storage/framework/sessions/. Expired files are removed by a probabilistic garbage-collection sweep controlled by session.lottery.
Sessions are stored in a sessions table. The StartSession middleware detects whether the table exists and falls back to the file driver if it does not. Required schema (created by the bundled migration):
CREATE TABLE sessions (
id VARCHAR(255) PRIMARY KEY,
user_id INTEGER,
payload TEXT NOT NULL,
last_activity INTEGER NOT NULL
);Expired rows are removed by a lottery-triggered DELETE WHERE last_activity < ?.
Sessions are stored as Base64-encoded Erlang terms in Redis with an EX TTL derived from session.lifetime. The session key format is laravex:session:{session_id}.
SESSION_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
Garbage collection is handled natively by Redis TTL — gc_expired/1 is a no-op for the Redis driver.
Limitations: no TLS, no Cluster, no password auth over the wire in the current transport layer.
Session handling is wired into the web middleware group by default. Two middleware modules cooperate:
| Module | Responsibility |
|---|---|
Laravex.Http.Middleware.StartSession |
Reads the session cookie, loads the session into the request struct, resolves the authenticated user |
Laravex.Http.Middleware.VerifyCsrfToken |
Generates and validates the _token CSRF token stored in the session |
The kernel calls Laravex.Session.Store.save/2 automatically at the end of every web request and sets the session cookie on the response.
The session is a plain Elixir map stored on the request struct at request.session. Use the Laravex.Session.Store helpers to read and write it:
alias Laravex.Session.Store
# Read a value (returns nil when absent)
value = Store.get(request, "key")
value = Store.get(request, "key", "default")
# Read all session data
all = Store.all(request)
# => %{"key" => value, …}
# Read a subset of keys
subset = Store.only(request, ["user_id", "locale"])
# Write a value (returns an updated request)
request = Store.put(request, "key", value)
# Remove a key
request = Store.forget(request, "key")
# Get a value and remove it atomically
{value, request} = Store.pull(request, "key")
{value, request} = Store.pull(request, "key", "default_if_missing")Keys are always stringified — atom and string keys are equivalent.
Flash data persists for exactly one subsequent request. After that it is automatically aged out.
request = Store.flash(request, "status", "Profile updated!")In the next request's Blade template:
@session('status')
<div class="alert alert-success">{{ $value }}</div>
@endsessionrequest = Store.flash_now(request, "status", "Saved!")flash_now writes the value to request.flash (available in the current view) without persisting it to the session for the next request.
# Keep specific flash keys alive for one more request
request = Store.keep(request, ["status", "errors"])
# Keep ALL current flash data for one more request
request = Store.reflash(request)The kernel calls Laravex.Session.Store.age_flash/1 internally. Flash data written with Store.flash/3 becomes available as old in the next request and is discarded on the request after that.
The controller helpers (via use App.Http.Controllers.Controller) provide convenience wrappers:
# Redirect to a URL with a flash value
redirect_with("/dashboard", %{status: "Settings saved."})
# Redirect back with old input (used automatically on validation failure)
redirect_with_input("/form")Replace the current session ID while keeping session data — useful after login to prevent session-fixation attacks:
request = Store.regenerate(request)regenerate/1 saves the current session under a new ID, deletes the old ID from the backend, and returns an updated request with session_id set to the new value.
# Clear all session data but keep the session ID
request = Store.flush(request)
# Clear all session data AND regenerate the session ID (Laravel `invalidate`)
request = Store.invalidate(request)The HTTP kernel stores the previous request URL in the session automatically:
# Retrieve the previous URL (e.g. for a "back" link)
Store.previous_url(request)
Store.previous_url(request, "/fallback")request.session_id # => "abc123..."The CSRF token is stored in the session under the "_token" key and injected into every view automatically:
@csrf
{{-- renders: <input type="hidden" name="_token" value="..."> --}}
{{ csrf_token() }}
{{-- renders the token string --}}The VerifyCsrfToken middleware checks params["_token"], the x-csrf-token header, or the x-xsrf-token header on all state-changing requests (POST, PUT, PATCH, DELETE). A mismatch returns a 419 Page Expired response.
Exempt specific paths by configuring :csrf_except in your application config:
config :laravex, csrf_except: ["/webhooks/stripe", "/api/inbound"]The paths "/" and "/up" are always exempt.
- CSRF-Protection — full CSRF reference
-
Requests — session data on the request struct (
request.session,request.flash) - Responses — session cookie written to the response
- Limitations — Redis transport constraints
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