Introduction to the ā419 Page Expiredā error in Laravel
Have you ever used HTTP code 419 in your Laravel applications and received the “Page Expired” error?
Often, it’s a straightforward problem with tokens connected to Cross-Site Request Forgery (CSRF).
Let’s examine its meaning and potential solutions.
Why ā419 Page Expiredā happens and how to fix it
Regardless of the version you are using, you have probably used the @csrf directive in your forms in your Laravel 8, 9, or 10 applications.
When the form is submitted, this directive creates a hidden input field with a CSRF token in it.
This token verifies that you, and not a third party, are submitting the form from your application.
When the CSRF token is mismatched, errors like “419 Page Expired” happen. This may occur for a number of reasons:
When a page, such a login page, is left open for an extended period of time, the token expires, which is a good thing. Simply use the browser’s refresh button to send the form again.
Another reason could be that you neglected to include the @csrf directive.
Learn more on Laravelās documentation aboutĀ Cross-Site Request Forgery protection.
Disable CSRF protection on some pages to avoid the ā419 Page Expiredā error
Occasionally, you may want to disable CSRF protection on some pages and kill those ā419 Page Expiredā errors.
Instead of removing the middleware from the kernel, specify which pages you want to exclude from being protected.
InĀ app/Http/Middleware/VerifyCsrfToken.php:
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
'/some-page',
'/some-other-page',
];
}