Laravel auto-login when website closed

Posted on

Automatically login when website closed laravel chrome

How to make Laravel auto-login every time the website is closed (e.g. browser is closed or session expires)?. In this context, we want to make sure the user session does not last long and they have to re-authenticate. Here are the steps:

Edit Laravel Session Configuration

Laravel uses a built-in session system that can be set in the config/session.php configuration file. To ensure that users have to re-login every time the website is closed, you can set sessions to expire when the browser is closed.

  • Open the config/session.php file.
  • Make sure the following options are set:
DEFAULT:
'lifetime' => env('SESSION_LIFETIME', 120), // Life time in minutes (result is 120 minutes)
'expire_on_close' => true, // Session ends when browser is closed

CHANGE TO:
'lifetime' => 1, // Session lifetime in minutes (e.g. 1 minute)
'expire_on_close' => true, // Session ends when browser is closed

With expire_on_close set to true, the session will be automatically deleted when the user closes the browser, so they will have to re-login when they return to the website.

Other ways you can try are:

  • Using Middleware Auth
  • Disable “Remember Me”
  • Automatic Logout when the session ends

Additional Notes:

  1. If you are using Laravel with a SPA frontend (e.g. Vue or React), make sure your authentication tokens (e.g. Sanctum) are also set to expire as needed.
  2. Adjust the lifetime in config/session.php if you want the session to stay alive for a certain amount of time even if the browser is not closed.