getSession returns null in api calls, but is alright in getServerSideProps #2684
-
Before my page starts, I make a api call to get data from database and send this info to the page as parameters. I am using localization which depends on use of So it is fine in pages/index.tsx export default fucntion Index({info}: Props)
{
return <div>{info}</div>
}
export async function getServerSideProps({ req, locale }: NextPageContext) {
const session = await getSession({ req });
// here session has value
console.log("session", session);
// making an api call to test endpoint
const info = await fetch(`${process.env.NEXTAUTH_URL}/api/test`).then((res) => res.json());
return {
props: {
info
},
};
} pages/api/test.ts export default async function Test(req: NextApiRequest, res: NextApiResponse) {
await ConnectToDB();
if(req.method === "GET")
{
const session = await getSession({ req });
// here session is null
console.log("session", session);
const info = Info.findOne({session?.user?.email})
res.status(200).end(JSON.stringify({ info }));
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You should just move this logic: const info = Info.findOne({session?.user?.email}) directly into getServerSideProps. It is generally not recommended to fetch your api from getServerSideProps. You can create a shared module if you still need that api endpoint for other reasons instead. Ref: https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering Check the Note |
Beta Was this translation helpful? Give feedback.
You should just move this logic:
directly into getServerSideProps.
It is generally not recommended to fetch your api from getServerSideProps.
You can create a shared module if you still need that api endpoint for other reasons instead.
Ref: https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
Check the Note