You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Sep 24, 2025. It is now read-only.
The new AuthProvider implements cross-tab and server-client session synchronization using refresh tokens and event listeners. The logic for detecting session changes and refreshing the page is complex and critical for authentication consistency. The reviewer should carefully validate that session state is always accurate, that router.refresh() is only called when necessary, and that there are no race conditions or edge cases (e.g., rapid tab switching, session expiration, or sign-out in another tab) that could cause stale or inconsistent authentication state.
exportconstAuthProvider=({ children }: AuthProviderProps)=>{const[user,setUser]=useState<Session["user"]|null>(null);const[session,setSession]=useState<Session|null>(null);const[isLoading,setIsLoading]=useState<boolean>(true);const[isAuthenticated,setIsAuthenticated]=useState<boolean>(false);constlastRefreshTokenIdRef=useRef<string|null>(null);constrouter=useRouter();// Initialize Nhost client with cookie-based storage for server/client session sharingconstnhost=useMemo(()=>createClient({region: process.env["NHOST_REGION"]||"local",subdomain: process.env["NHOST_SUBDOMAIN"]||"local",storage: newCookieStorage({secure: process.env.NODE_ENV==="production",sameSite: "lax",}),}),[],);/** * Handles session reload when refresh token changes. * This detects when the session has been updated by middleware or other tabs. * * @param currentRefreshTokenId - The current refresh token ID to compare against stored value */constreloadSession=(currentRefreshTokenId: string|null)=>{if(currentRefreshTokenId!==lastRefreshTokenIdRef.current){lastRefreshTokenIdRef.current=currentRefreshTokenId;// Update local authentication state to match current sessionconstcurrentSession=nhost.getUserSession();setUser(currentSession?.user||null);setSession(currentSession);setIsAuthenticated(!!currentSession);// Trigger Next.js page refresh to sync server-side state with client changesrouter.refresh();}};// Initialize authentication state and set up cross-tab session synchronizationuseEffect(()=>{setIsLoading(true);// Load initial session state from Nhost clientconstcurrentSession=nhost.getUserSession();setUser(currentSession?.user||null);setSession(currentSession);setIsAuthenticated(!!currentSession);lastRefreshTokenIdRef.current=currentSession?.refreshTokenId??null;setIsLoading(false);// Subscribe to session changes from other browser tabs// This enables real-time synchronization when user signs in/out in another tabconstunsubscribe=nhost.sessionStorage.onChange((session)=>{reloadSession(session?.refreshTokenId??null);});returnunsubscribe;},[nhost]);// Handle session changes from server-side middleware and page focus eventsuseEffect(()=>{/** * Checks for session changes when page becomes visible or focused. * This catches middleware-driven session updates that occur server-side. */constcheckSessionOnFocus=()=>{reloadSession(nhost.getUserSession()?.refreshTokenId??null);};// Monitor page visibility changes (tab switching, window minimizing)document.addEventListener("visibilitychange",()=>{if(!document.hidden){checkSessionOnFocus();}});// Monitor window focus events (clicking back into the browser window)window.addEventListener("focus",checkSessionOnFocus);// Cleanup event listeners on component unmountreturn()=>{document.removeEventListener("visibilitychange",checkSessionOnFocus);window.removeEventListener("focus",checkSessionOnFocus);};},[nhost,router]);
The Nhost client initialization uses process.env variables with "local" as a fallback. The reviewer should ensure that these fallbacks are appropriate for all deployment scenarios and that sensitive configuration is not accidentally exposed or misconfigured, especially in production.
The AuthProvider now wraps the entire application layout, including Navigation and main content. The reviewer should verify that this does not introduce hydration mismatches or unexpected context propagation issues in Next.js, particularly with server/client component boundaries.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR Type
Enhancement, Documentation
Description
Introduce
AuthProviderfor robust client-side auth context in Next.js demoEnable cross-tab and server-client session synchronization via refresh token
Refactor all client components to use new
useAuthhookImprove and document session handling in React/React-Apollo/React-Query guides
Changes walkthrough 📝
10 files
Add advanced AuthProvider for client-side auth/session syncWrap app in AuthProvider for global auth contextRefactor to use useAuth instead of direct client creationRefactor to use useAuth for Nhost client accessRefactor to use useAuth for Nhost client accessRefactor to use useAuth for Nhost client accessRemove obsolete direct Nhost client creation utilityEnhance AuthProvider with session sync and documentationEnhance AuthProvider with session sync and documentationEnhance AuthProvider with session sync and documentation1 files
Document AuthProvider and session sync in Next.js demo