Skip to content

Instantly share code, notes, and snippets.

@admench
Created May 9, 2025 14:08
Show Gist options
  • Save admench/5ebef44645839c6601b0f02e9e371289 to your computer and use it in GitHub Desktop.
Save admench/5ebef44645839c6601b0f02e9e371289 to your computer and use it in GitHub Desktop.
useSessionCheck.ts Vue composable
# .env
SESSION_LIFETIME=2
<script lang="ts" setup>
const props = defineProps<BasePageProps>()
useSessionCheck(props)
</script>
public function share(Request $request): array
{
return [
...parent::share($request),
'auth' => [
'session' => [
'expires' => now()->addMinutes(config('session.lifetime'))->setTimezone('Europe/London')->toDateTimeString(),
],
],
];
}
// useSessionCheck composable:
import type { BasePageProps } from '@/types'
import { toast } from '@/components/ui/toast'
import { router } from '@inertiajs/vue3'
import { useDocumentVisibility } from '@vueuse/core'
import { watch } from 'vue'
/*
* If the user returns to the tab after a period of inactivity,
* check if the session has expired. If so, reload page
* (which will redirect to login page with intended
* url stored in session).
*/
export function useSessionCheck(props: BasePageProps) {
const expires = props.auth.session.expires
const expiresDate = new Date(expires)
const visibility = useDocumentVisibility()
watch(visibility, (visible) => {
if (visible === 'visible') {
const now = new Date()
if (expiresDate < now) {
toast({ title: 'Session expired', description: 'Please login again' })
router.reload()
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment