How to resolve the Laravel “419 Page Expired” problem.

Posted by

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',
    ];
}

Leave a Reply

Your email address will not be published. Required fields are marked *

0
Would love your thoughts, please comment.x
()
x