I encountered an issue while using the getServerSideProps function in Next.js with Next-Auth. The error I received was a TypeError:
TypeError: Cannot destructure property 'nextauth' of 'req.query' as it is undefined.
Upon checking with the console, it confirmed that the value is indeed undefined.
I have been referring to the official documentation for NextAuth.js: https://next-auth.js.org/configuration/nextjs#getserversession
This is my function:
export const getServerSideProps = async (context: { req: NextApiRequest; res: NextApiResponse<any>; }) => {
const session = await getServerSession(context.req, context.res, authOptions)
if (!session) {
return {
redirect: {
destination: '/',
permanent: false
}
}
}
return {
props: {
session,
}
}
}
When I run this code:
const {req: query} = context
console.log(query == undefined)
The console output indicates false, yet the TypeError persists.
If I modify the function's parameters like so:
export const getServerSideProps = async (req: NextApiRequest, res: NextApiResponse<any>) => {
const session = await getServerSession(req, res, authOptions)
if (!session) {
return {
redirect: {
destination: '/',
permanent: false
}
}
}
return {
props: {
session,
}
}
}
I encounter a different error:
My _App: TypeError: Cannot read properties of undefined (reading 'x-forwarded-host')
export default function App({
Component, pageProps: { session, ...pageProps}}: AppProps, {emotionCache = clientSideEmotionCache,}){
return (
<SessionProvider session={pageProps.session}>
<CacheProvider value={emotionCache}>
<ThemeProvider theme={lightTheme}>
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
</SessionProvider>
);
};
Any suggestions on how to proceed?