Skip to content

CSRF Protection

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

CSRF Protection

Laravex protects all state-changing requests (anything that is not GET, HEAD, or OPTIONS) against Cross-Site Request Forgery attacks using the VerifyCsrfToken middleware, which is included in the "web" Middleware group by default.

How It Works

  1. When a GET or HEAD request arrives, VerifyCsrfToken ensures a random token is stored in the session under the key "_token". If none exists it generates one with str_random(40).
  2. For POST, PUT, PATCH, and DELETE requests the middleware checks that a token submitted with the request matches the session token using a constant-time comparison (crypto.hash_equals).
  3. If the token is missing or does not match the response is a 419 Page Expired.

Including the Token in Forms

Use the @csrf Blade directive inside any HTML form to emit a hidden input field:

<form method="POST" action="/posts">
  @csrf
  <!-- renders: <input type="hidden" name="_token" value="<token>"> -->
  ...
</form>

You can also output the raw token value with {{ csrf_token() }} in a Blade template, which is useful for embedding the token in <meta> tags for JavaScript clients:

<meta name="csrf-token" content="{{ csrf_token() }}">

Submitting the Token from JavaScript

Axios and other HTTP clients can read the token from the X-CSRF-TOKEN header or the X-XSRF-TOKEN cookie. VerifyCsrfToken accepts the token from any of the following locations (checked in order):

  1. request.params["_token"] (form field)
  2. X-CSRF-TOKEN request header
  3. X-XSRF-TOKEN request header

Excluding URIs from CSRF Verification

Certain paths — such as webhook receivers — need to be exempt from CSRF checks. Configure exclusions in your application config or via Application.get_env:

# config/config.exs (or any environment config)
config :laravex, csrf_except: [
  "/stripe/webhook",
  "/github/webhook"
]

The paths "/" and "/up" (the health-check endpoint) are always excluded automatically.

Method Spoofing

HTML forms only support GET and POST. To submit a PUT, PATCH, or DELETE request from a form, use the @method directive alongside @csrf:

<form method="POST" action="/posts/1">
  @csrf
  @method('DELETE')
  <button type="submit">Delete Post</button>
</form>

The MethodOverride middleware (part of the "web" group) reads the _method field and updates request.method accordingly before the route is dispatched.

Clone this wiki locally