Auto Redirect to Login Page on Laravel Page Expired

Auto Redirect to Login Page on Laravel Page Expired

In Laravel, when the CSRF token has expired, the app usually shows a 419|Page Expired error.

To auto-redirect to the login page when a Laravel page expires, we can modify the App\Exceptions\Handler file. This file handles all exceptions that are thrown in our Laravel application.

Auto-redirecting users to the login page when their session expires prevents them from seeing the page expired warning, thereby improving the user experience, especially for users logged in for extended periods.

In Laravel, preventing the display of the page expired warning and automatically redirecting users to the login page can be achieved with the steps below:

Steps:

  1. Open the App\Exceptions\Handler file.

  2. Locate the register function within the Handler class.

  3. Insert the following code snippet into the register function just below the $this->reportable closure:

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

This code will check if the exception is a TokenMismatchException. This exception is thrown when the CSRF token has expired. The code will redirect the user to the login page if it is.

Your register function should now look like this:

public function register(): void
{
    $this->reportable(function (Throwable $e) {
        //
    });

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

With this code in place, Laravel will automatically redirect users to the login page when a session token mismatch exception occurs, preventing the page expired warning from being displayed.

Note: All code tested using Laravel 10