Reputation: 1
I'm currently facing an issue with retrieving the session on the server side while using next-auth in Next.js. On the client side, when I utilize the useSession hook, I can successfully obtain the session object. However, when I attempt to retrieve the session using getSession or getServerSession on the server side, I constantly receive undefined.
Next.js v13.4.6 NextAuth v4.22.1 React v18.2
export async function getServerSideProps({req, res}) {
const session = await getSession(req);
const serverSession = await getServerSession(request, response, authOptions);
return {
props: {
session,
serverSession
},
};
}
export default function App({ Component, pageProps: {session, serverSession,...pageProps } })
{
console.log(session); //undefined
console.log(serverSession); //undefined
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
I have carefully followed the documentation provided by both Next.js and next-auth, but I am still unable to resolve this problem. Could anyone please help me understand why I am encountering this issue and provide guidance on how to retrieve the session correctly on the server side using next-auth in Next.js?
Upvotes: 0
Views: 2965
Reputation: 1
I managed to resolve this problem.
The thing was that the .env file wasn't configured correctly. After I updated the URL, everything works fine.
Upvotes: 0
Reputation: 49571
this is getSession
type
export declare function getSession(params?: GetSessionParams): Promise<Session | null>;
this is GetSessionParams
:
export declare type GetSessionParams = CtxOrReq & {
event?: "storage" | "timer" | "hidden" | string;
triggerEvent?: boolean;
broadcast?: boolean;
};
this is CtxOrReq
export interface CtxOrReq {
req?: IncomingMessage;
ctx?: {
req: IncomingMessage;
};
}
As you see getSession
receives an object. so you should
const session = await getSession({ req:req })
Upvotes: 0