From f498e9cd0a03bdb4d5383dedc657ac33c5354361 Mon Sep 17 00:00:00 2001 From: Matthew Francis Brunetti Date: Sat, 5 Nov 2022 18:06:34 -0400 Subject: [PATCH] fix(react): allow imports from "next-auth/react" in RSC (#5718) --- packages/next-auth/src/react/index.tsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/next-auth/src/react/index.tsx b/packages/next-auth/src/react/index.tsx index aee30350aa..07f1f199c9 100644 --- a/packages/next-auth/src/react/index.tsx +++ b/packages/next-auth/src/react/index.tsx @@ -95,7 +95,7 @@ export type SessionContextValue = R extends true | { data: Session; status: "authenticated" } | { data: null; status: "unauthenticated" | "loading" } -export const SessionContext = React.createContext< +export const SessionContext = React.createContext?.< SessionContextValue | undefined >(undefined) @@ -106,6 +106,10 @@ export const SessionContext = React.createContext< * [Documentation](https://next-auth.js.org/getting-started/client#usesession) */ export function useSession(options?: UseSessionOptions) { + if (!SessionContext) { + throw new Error("React Context is unavailable in Server Components") + } + // @ts-expect-error Satisfy TS if branch on line below const value: SessionContextValue = React.useContext(SessionContext) if (!value && process.env.NODE_ENV !== "production") { @@ -322,6 +326,10 @@ export async function signOut( * [Documentation](https://next-auth.js.org/getting-started/client#sessionprovider) */ export function SessionProvider(props: SessionProviderProps) { + if (!SessionContext) { + throw new Error("React Context is unavailable in Server Components") + } + const { children, basePath, refetchInterval, refetchWhenOffline } = props if (basePath) __NEXTAUTH.basePath = basePath