Laravel 419 Page Expired Explained

June 17th, 2024 • 2 minutes read time

You might be getting a 419 Expired error in Laravel for a couple of reasons. Let's dive into why this may happen and how to fix it.

Want to level up in Laravel? We create practical screencasts to help you build.

Every POST, PATCH, PUT and DELETE request that originates from a form in Laravel requires a Cross-Site Request Forgery token to be set. If you try to post a form in Laravel without this token, you'll see a 419 Page Expired error.

This is an incredibly important security measure to be sure that the user posting the form is actually that user.

To fix the 419 Page Expired error for any of your forms, use the @csrf directive in Blade.

<form action="/somewhere" method="post">
    @csrf
    <!-- Your form fields -->
    <button type="submit">Submit</button>
</form>

Once this form is submitted, the CSRF token will be checked, and you'll no longer see a 419 error.

Because CSRF tokens are fairly short-lived, staying on a page for too long without refreshing means the token will eventually expire, and you (or your users) will see the same 419 error.

I wouldn't recommend increasing the lifespan of the CSRF token. Instead, create a custom 419 error page to explain to the user what happened and what they should do next.

To do this, create a resources/views/errors/419.blade.php file in your Laravel project and add any information for your user.

<h1>Page expired</h1>
<p>The page has expired. Please go back and try again.</p>

By overriding the default 419 error, you can explain to the user what they need to do.

There are certain routes that you may not want to protect with CSRF, so you can get rid of the 419 Page Expired error by excluding paths. I would only recommend doing this for routes where you're physically unable to generate a CSRF token... like a webhook from an external service.

To disable CSRF token checks in Laravel 11, open up your bootstrap/app.php file and add the following code under the withMiddleware method:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/*',
    ]);
})

The example above disabled CSRF protection for all endpoints starting with stripe/.

If you're not using Laravel 11, you can do the same thing by opening up the VerifyCsrfToken middleware and updating the $except property.

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'stripe/*'
    ];
}

I hope this has helped you understand what causes a 419 Page Expired error in Laravel, and that you're able to handle forms properly, warn your users, or disable CSRF checks where needed.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!