How to Fix CodeIgniter 4 CSRF Token Failures in AJAX Forms
CodeIgniter 4's built-in CSRF protection regenerates a new token after every request, which causes AJAX form submissions to fail with 419 or 'Page Expired' errors if the token is not refreshed client-side. The core issue is that most AJAX implementations send the initial token but never update it after the first response, making all subsequent requests invalid. To resolve this, developers should set '$redirect = false' in the Security config so CI4 returns a proper JSON error instead of redirecting, and controllers should return the new CSRF token in every AJAX response. A global jQuery setup using 'ajaxSetup' can then intercept all POST requests and automatically attach the latest token, eliminating the need to handle it form by form. This approach covers single forms, multiple forms, and app-wide AJAX configurations in production CodeIgniter 4 projects.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in