Laravel 5.x.x - 4 Steps to Prevent Browser's Back Button After User Logout

Laravel 5.x.x 4 Steps to Prevent Browser's Back Button After User Logout

Well, have you found out an issue with user logout? If you observe deeply then you can found out this issue that you can logout properly after you click logout link otherwise than if you click on browser’s back button you still able to see the content of the page which actually should not be seen with respect to auth middleware process.

We can prevent this issue by using Laravel middleware. We will create one middleware and prevent back button history. So we have to create new middleware and use that middleware in the route.

Like so, I am going to do from scratch so:

1. Create New Middleware
Create a new middleware using following command:

1
php artisan make:middleware PreventBackHistory

2. Middleware Configuration
Open up PreventBackHistory.php file in app/Http/Middleware folder and replace codes with the following codes below:

PreventBackHistory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace App\Http\Middleware;

use Closure;

class PreventBackHistory {
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next) {
    $response = $next($request);

    return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
  }
}

3. Register Middleware
Open Kernel.php in app/Http folder and add a new middleware in $routeMiddleware variable array as below:

Kernel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {
  .....
  .....

  /**
   * The application's route middleware.
   *
   * These middleware may be assigned to groups or used individually.
   *
   * @var array
   */
  protected $routeMiddleware = [
    .....

    'prevent-back-history' => \App\Http\Middleware\PreventBackHistory::class,
  ];

}

4. Use Middleware in Route
Now we are ready to use “prevent-back-history” middleware in route file as below:

web.php
1
2
3
4
Route::group(['middleware' => 'prevent-back-history'],function(){
  Auth::routes();
  Route::get('/home', 'HomeController@index');
});

So far so good, That’s it!!! See ya!!! :)