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
I'm dealing with a client-side session caching mismatch between NextAuth's useSession hook and our server-side session validation. We're leveraging SWR, which has built-in rehydration of endpoints when a user reopens a prolonged inactive browser session within our app.
We have middleware to check client-side if the session is valid via useSession before attempting to hit our API. However, since the session is cached, it shows the status as authenticated. We then hit our endpoints, which attempt to use the cached (and now expired) session, resulting in a spam of errors.
Below is a snippet of what we wish we could do (rely on useSession's status)
import { useSession } from 'next-auth/react'
import useSWR, { SWRConfiguration, SWRResponse } from 'swr'
// This custom hook behaves like useSWR, but only starts fetching
// if the session is fully loaded and authenticated.
export function useSWRWithSession<Data = unknown, Error = unknown>(
key: string | null,
fetcher: (url: string) => Promise<Data>,
config?: SWRConfiguration<Data, Error>
): SWRResponse<Data, Error> {
const { status } = useSession()
// Only allow fetching if the session is authenticated
const validKey = status === 'authenticated' && key ? key : null
return useSWR<Data, Error>(validKey, fetcher, config)
}
Are there any ways to address this client/server session discrepancy?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi,
I'm dealing with a client-side session caching mismatch between NextAuth's
useSession
hook and our server-side session validation. We're leveragingSWR
, which has built-in rehydration of endpoints when a user reopens a prolonged inactive browser session within our app.We have middleware to check client-side if the session is valid via useSession before attempting to hit our API. However, since the session is cached, it shows the status as authenticated. We then hit our endpoints, which attempt to use the cached (and now expired) session, resulting in a spam of errors.
Below is a snippet of what we wish we could do (rely on useSession's
status
)Are there any ways to address this client/server session discrepancy?
Beta Was this translation helpful? Give feedback.
All reactions