How to fix the 419 page expired error in Laravel?

The Session Expired or 419 Page Expired error message in Laravel comes up because somewhere your csrf token verification fails.

To fix this error in Laravel, you have to use the CSRF token carefully in your project.

  • Add CSRF in your Form to prevent page expired error
  • Add CSRF to head and script prevent 419 error
  • Disable CSRF Protection to prevent 419 error
  • Solution to 419 page expired after logout in Laravel 8

CSRF makes it easy for Laravel to protect an application from cross-site request forgery (CSRF) attacks’.

Below we will discuss some cases when Laravel shows page expired error and their appropriate solution.

Add CSRF in your Form to prevent page expired error

You may forgot to add @csrf in your form. So, if you get the page expired error after submitting a form, then you need to add the CSRF field in your form.

<form method="post">
@csrf
</form>

Add CSRF to head and script prevent 419 error

If you are getting the 419 Page expired error after you call the AJAX then you need to add a header as shown below.

<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
//if not work
composer dump-autoload

You can also add the token in your script tag as shown below.

$.ajaxSetup({
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

Disable CSRF Protection to prevent 419 error

Another solution is to disable CSRF protection. You can do this for routes group or specific routes

Open the file VerifyCsrfToken.php on your project in the directory – App\Http\Middleware\VerifyCsrfToken.php.

Note: this method will only works for webhooks.

<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
  protected $except = [
    'payment/*', // routes group
    'specific-route', // specific route
  ];
}

Solution to 419 page expired after logout in Laravel 8

In laravel 8, you might see, when you logout of laravel application you land on logout page with error status 419 | page expired. This usually happens when you try logging out from laravel application after in activity on application for some time.

Solution

Adding following piece of code in your App\Exceptions\Handler.php class, within the register() method, will fix this issue

$this->renderable(function (\Exception $e) {
    if ($e->getPrevious() instanceof \Illuminate\Session\TokenMismatchException) {
        return redirect()->route('login');
    };
});

Coder Expert

I am full-stack developers at Scratch Coding. We are passionate to write tutorials and tips that can help other developers. We are very much into PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap. We believe in Hardworking and Consistency.

Follow Me:

Leave a Comment