Skip to content

Controller

authenticityToken()

authenticityToken() — returns string

Available in: controller Category: Miscellaneous Functions

Returns the raw CSRF authenticity token for the current user session. This token is used to help protect against Cross-Site Request Forgery (CSRF) attacks by verifying that form submissions or AJAX requests originate from your application. You typically won’t call this function directly in views — instead, Wheels provides helpers like authenticityTokenField() to generate hidden form fields. But authenticityToken() can be useful if you need direct access to the token string (for example, in custom JavaScript code).

1. Get the raw CSRF token in a controller
token = authenticityToken();

2. Output token manually in a form (not recommended, but possible)
<form action="/posts/create" method="post">
    <input type="hidden" name="authenticityToken" value="#authenticityToken()#">
    <input type="text" name="title">
    <input type="submit" value="Save">
</form>

3. Use in AJAX request headers
fetch("/posts/create", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-CSRF-Token": "#authenticityToken()#"
  },
  body: JSON.stringify({ title: "New Post" })
});