diff --git a/src/components/LogoutOnUnload.tsx b/src/components/LogoutOnUnload.tsx index 47d4879..84dc3ea 100644 --- a/src/components/LogoutOnUnload.tsx +++ b/src/components/LogoutOnUnload.tsx @@ -1,17 +1,40 @@ 'use client'; -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useCart } from '@/lib/cartStore'; /** * Logs out the user when they close/leave the page * Works for both admin and customer sessions + * Skips logout when navigating to external checkout (Stripe, etc) */ export default function LogoutOnUnload() { const clearCart = useCart((s) => s.clear); + const isCheckingOut = useRef(false); + + useEffect(() => { + // Mark when checkout is being initiated + const origFetch = window.fetch; + window.fetch = function(...args) { + const url = typeof args[0] === 'string' ? args[0] : (args[0] as Request).url; + if (url?.includes('/api/checkout')) { + isCheckingOut.current = true; + } + return origFetch.apply(this, args); + }; + + return () => { + window.fetch = origFetch; + }; + }, []); useEffect(() => { const handleUnload = () => { + // Don't logout if we're in the middle of checkout (navigating to Stripe) + if (isCheckingOut.current) { + return; + } + // Clear cart on logout clearCart(); // Use sendBeacon to reliably send logout even when page is closing