MCPcopy
hub / github.com/nextauthjs/next-auth / SessionProvider

Function SessionProvider

src/react/index.tsx:297–423  ·  view source on GitHub ↗
(props: SessionProviderProps)

Source from the content-addressed store, hash-verified

295 * [Documentation](https://next-auth.js.org/getting-started/client#sessionprovider)
296 */
297export function SessionProvider(props: SessionProviderProps) {
298 const { children, basePath } = props
299
300 if (basePath) __NEXTAUTH.basePath = basePath
301
302 /**
303 * If session was `null`, there was an attempt to fetch it,
304 * but it failed, but we still treat it as a valid initial value.
305 */
306 const hasInitialSession = props.session !== undefined
307
308 /** If session was passed, initialize as already synced */
309 __NEXTAUTH._lastSync = hasInitialSession ? now() : 0
310
311 const [session, setSession] = React.useState(() => {
312 if (hasInitialSession) __NEXTAUTH._session = props.session
313 return props.session
314 })
315
316 /** If session was passed, initialize as not loading */
317 const [loading, setLoading] = React.useState(!hasInitialSession)
318
319 React.useEffect(() => {
320 __NEXTAUTH._getSession = async ({ event } = {}) => {
321 try {
322 const storageEvent = event === "storage"
323 // We should always update if we don't have a client session yet
324 // or if there are events from other tabs/windows
325 if (storageEvent || __NEXTAUTH._session === undefined) {
326 __NEXTAUTH._lastSync = now()
327 __NEXTAUTH._session = await getSession({
328 broadcast: !storageEvent,
329 })
330 setSession(__NEXTAUTH._session)
331 return
332 }
333
334 if (
335 // If there is no time defined for when a session should be considered
336 // stale, then it's okay to use the value we have until an event is
337 // triggered which updates it
338 !event ||
339 // If the client doesn't have a session then we don't need to call
340 // the server to check if it does (if they have signed in via another
341 // tab or window that will come through as a "stroage" event
342 // event anyway)
343 __NEXTAUTH._session === null ||
344 // Bail out early if the client session is not stale yet
345 now() < __NEXTAUTH._lastSync
346 ) {
347 return
348 }
349
350 // An event or session staleness occurred, update the client session.
351 __NEXTAUTH._lastSync = now()
352 __NEXTAUTH._session = await getSession()
353 setSession(__NEXTAUTH._session)
354 } catch (error) {

Callers

nothing calls this directly

Calls 2

nowFunction · 0.90
getSessionFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…