![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/lavocat.quebec/private_html/src/utils/ |
/**
* Utility to automatically clean up invalid sessions
* This helps when NEXTAUTH_SECRET changes and old cookies become invalid
*/
export interface SessionCleanupOptions {
autoRedirect?: boolean;
redirectUrl?: string;
onCleanup?: () => void;
}
/**
* Check if we need to clean up the session
* Call this from client-side pages that require authentication
*/
export function checkAndCleanupSession(options: SessionCleanupOptions = {}) {
if (typeof window === 'undefined') return;
const {
autoRedirect = true,
redirectUrl = '/auth/login',
onCleanup
} = options;
// Check for NextAuth error in URL
const urlParams = new URLSearchParams(window.location.search);
const error = urlParams.get('error');
if (error === 'SessionRequired' || error === 'AccessDenied') {
console.log('🧹 Invalid session detected, cleaning up...');
// Clear all NextAuth cookies
const cookiesToClear = [
'next-auth.session-token',
'__Secure-next-auth.session-token',
'next-auth.csrf-token',
'next-auth.callback-url',
'__Secure-next-auth.csrf-token'
];
cookiesToClear.forEach(cookieName => {
// Clear for current path
document.cookie = `${cookieName}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=${window.location.hostname}`;
// Clear for specific paths
document.cookie = `${cookieName}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = `${cookieName}=; path=/api; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
});
// Call cleanup callback
if (onCleanup) {
onCleanup();
}
// Optional: redirect to login
if (autoRedirect) {
setTimeout(() => {
window.location.href = redirectUrl;
}, 100);
}
return true;
}
return false;
}
/**
* Call from _app.tsx or specific pages to auto-clean invalid sessions
*/
export function setupAutoSessionCleanup(options: SessionCleanupOptions = {}) {
if (typeof window === 'undefined') return;
// Run on page load
checkAndCleanupSession(options);
// Also listen for NextAuth events
window.addEventListener('storage', (e) => {
if (e.key === 'next-auth.error') {
checkAndCleanupSession(options);
}
});
}