Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ManojKiranA/f87ef09dd39184ea4469eef6c186b0b5 to your computer and use it in GitHub Desktop.
Save ManojKiranA/f87ef09dd39184ea4469eef6c186b0b5 to your computer and use it in GitHub Desktop.
Laravel Livewire Turbolinks Blade component to keep session alive
//in the head
<x-session-timeout-alert-head :permanent="false" />
</head>
//after livewire scripts
@livewireScripts
<x-session-timeout-alert-after-livewire-scripts />
</body>
{{-- You do not need to add this component if you are using the permanent option in the head component --}}
<script>
if(!window.sessionTimerPermanent) {
document.addEventListener('turbolinks:load', () => {
window.livewire.hook('afterDomUpdate', startSessionTimer);
}, {once: true})
}
</script>
@props([ 'permanent' => false ])
@php $session = config('session.lifetime'); @endphp
<script>
let sessionTimer = null
function clearTimer() {
clearTimeout(sessionTimer)
sessionTimer = null
}
function handleSessionWarning() {
alert('Your session will expire in 10 minutes due to inactivity! Click "OK" to avoid being logged out')
{{-- checkAuth() // runs automatically on window.focus after clicking the alert. Uncomment if you want to handleSessionWarning in a different way. --}}
}
function startSessionTimer() {
clearTimer()
sessionTimer = setTimeout(handleSessionWarning, 1000 * 60 * {{ $session - 10 }}) //Change this if your session is to short.
}
function checkAuth() {
if (document.hasFocus()) { //remove this if you want to keep the session alive even if the window is out of focus
// console.info('fetching')
fetch('/check-auth')
.then(response => response.text())
.then(auth => {
if (auth !== 'true') {
window.location.href = "{{ route('login') }}"
}
@if(!$permanent)
startSessionTimer()
@endif
})
}
}
@if($permanent)
window.sessionTimerPermanent = true;
setInterval(checkAuth, 1000 * 60 * {{ $session - 2 }})
@else
window.sessionTimerPermanent = false;
document.addEventListener('turbolinks:load', startSessionTimer);
@endif
window.addEventListener('focus', checkAuth);
</script>
Route::get('check-auth', fn () => response(auth()->check() ? 'true' : 'false'))->middleware('auth');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment