Skip to content

Instantly share code, notes, and snippets.

@tanthammar
Last active June 23, 2020 08:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tanthammar/88c7a28b68573f70dc3d09abb26d454b to your computer and use it in GitHub Desktop.
Save tanthammar/88c7a28b68573f70dc3d09abb26d454b to your computer and use it in GitHub Desktop.
Keep livewire form session alive (419)
<script data-turbolinks-eval=false>
function updateToken() {
fetch('/update-csrf')
.then(response => response.text())
.then(csrf => {
document.head.querySelector('meta[name="csrf-token"]').setAttribute('content', csrf)
})
}
setInterval(updateToken, 1000 * 60 * 5)
</script>
Route::get('update-csrf', fn () => response(csrf_token()))->middleware('auth');
@tanthammar
Copy link
Author

tanthammar commented Jun 18, 2020

add to your main app.blade.php or @push('scripts') on individual pages.

@booni3
Copy link

booni3 commented Jun 18, 2020

Does this keep the connection alive like caffeine, or will it allow the session to expire and auto-logout the user?

@tanthammar
Copy link
Author

It only works if the window is in focus!

If the user has multiple tabs open, and browses away from this one, the session expires any way. I can see in the console that the script keeps polling the server but I do not know why the session is terminated.

Suggestions?

@tanthammar
Copy link
Author

tanthammar commented Jun 20, 2020

redirect if logged out

Or if you do not want to return the csrf you could just check if the user is authenticated. The session token will be the same as long as the user is logged in. By polling the server the session is kept alive.

This one covers the situation where the window has lost its focus, the user will be redirected when they get back to the window.

Route::get('check-auth', fn () => response(auth()->check() ? 'true' : 'false'))->middleware('auth');
<script>
    document.addEventListener('turbolinks:load', () => {
        function checkAuth() {
            if (document.hasFocus()) { //do not spend money on dead requests
                fetch('/check-auth')
                .then(response => response.text())
                .then(auth => {
                    if(auth != "true") {
                        window.location.href="{{ route('login') }}";
                    }
                })
            }
        }
        setInterval(checkAuth, 1000 * 60 * 55) //every 55 minutes, my session is 120 minutes
        window.addEventListener('focus', () => {checkAuth()});
    }, {once: true}) //prevent turbolinks from running the script multiple times
</script>

@tanthammar
Copy link
Author

Here is an improved version, without csrf route
https://gist.github.com/tanthammar/02c615e73022c44dda6533ed9416ac29

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment