Skip to content

Session

David Ciulla edited this page Nov 7, 2026 · 2 revisions

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.


Configuration

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

Supported Drivers

File driver

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.

Database driver

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

Redis driver

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.


Middleware

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.


Reading and Writing Session Data

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

Flash data persists for exactly one subsequent request. After that it is automatically aged out.

Flash for the next request

request = Store.flash(request, "status", "Profile updated!")

In the next request's Blade template:

@session('status')
  <div class="alert alert-success">{{ $value }}</div>
@endsession

Flash for the current request only

request = 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 and Reflash

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

Flash aging

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.


Redirects with Flash

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

Session Regeneration

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.


Clearing Session Data

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

Previous URL

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

Accessing the Session ID

request.session_id   # => "abc123..."

CSRF Token

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.


Related

  • 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

Clone this wiki locally