Files
hats-app/providers/SessionProvider.tsx
T
Ichsan Kurniawan ff802a5b5d Deduplicate token refresh and sync sessions
Caches and deduplicates token refreshes, syncs refreshed tokens to the browser session, and updates auth configuration and documentation. Adds an RBAC requirements draft. The new credentials.md contains VPS credentials; remove it from the commit and rotate those credentials.
2026-11-13 15:01:46 +07:00

45 lines
1.3 KiB
TypeScript

'use client'
import { ReactNode, useEffect, useRef } from 'react';
import { type Session } from 'next-auth';
import { SessionProvider as Provider, useSession } from 'next-auth/react'
type Props = {
children: ReactNode,
session: Session | null
basePath?: string
};
function SessionSync() {
const { data: session, update } = useSession();
const isUpdatingRef = useRef(false);
useEffect(() => {
const user = session?.user as any;
if (!user) return;
// If the token was refreshed on the server during SSR / Server Components,
// the browser cookie was not updated because Server Components cannot set cookies.
// We trigger update() to hit /api/auth/session, which writes the updated Set-Cookie header.
if (user.is_refreshed && !isUpdatingRef.current) {
isUpdatingRef.current = true;
user.is_refreshed = false;
update().finally(() => {
isUpdatingRef.current = false;
});
}
}, [session, update]);
return null;
}
const SessionProvider: React.FC<Props> = ({ children, session, basePath }) => {
return (
<Provider session={session} basePath={basePath} refetchInterval={10 * 60}>
<SessionSync />
{children}
</Provider>
);
}
export default SessionProvider;