Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(react): support importing "next-auth/react" in Server Component environment #5718

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions packages/next-auth/src/react/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ export type SessionContextValue<R extends boolean = false> = R extends true
| { data: Session; status: "authenticated" }
| { data: null; status: "unauthenticated" | "loading" }

export const SessionContext = React.createContext<
SessionContextValue | undefined
>(undefined)
export const SessionContext = React.createContext
? React.createContext<SessionContextValue | undefined>(undefined)
: undefined

/**
* React Hook that gives you access
Expand All @@ -106,6 +106,10 @@ export const SessionContext = React.createContext<
* [Documentation](https://next-auth.js.org/getting-started/client#usesession)
*/
export function useSession<R extends boolean>(options?: UseSessionOptions<R>) {
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<R> = React.useContext(SessionContext)
if (!value && process.env.NODE_ENV !== "production") {
Expand Down Expand Up @@ -322,6 +326,10 @@ export async function signOut<R extends boolean = true>(
* [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
Expand Down