Using GetServerSideProps with Next-Auth: TypeError: Cannot destructure property 'nextauth' of 'req.query' as it is undefined
Asked Answered
P

4

6

I am using getServerSideProps function in next.js with Next-Auth and I'm getting a TypeError:

TypeError: Cannot destructure property 'nextauth' of 'req.query' as it is undefined.

When I checked using the console, it does indeed return undefined.

I have been following the official documentation for NextAuth.js: https://next-auth.js.org/configuration/nextjs#getserversession

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 do:

const {req: query} = context
console.log(query == undefined)

console returns false, but the TypeError is still there.

I receive a different error when I change the props for this function:

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,
    }
  }
}

The error then is:

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 what to do next?

Phenacite answered 3/2, 2023 at 9:20 Comment(1)
Why not export const getServerSideProps: GetServerSideProps = async (context) => {}Determinable
H
5

As @JujV pointed out, this is related to the new app router. But you don't have to "downgrade" to pages folder.

If you are declaring the routes like this: app/api/auth/[...nextauth]/page.ts

You should actually convert that to: app/api/auth/[...nextauth]/route.ts

I mean, use route, not page: https://nextjs.org/docs/app/building-your-application/routing/router-handlers

Hypnotist answered 25/5, 2023 at 17:49 Comment(0)
D
3

If you are using the latest version of next.js with nextAuth appDir, then the fix I did is to switch to the old pages/api/auth instead of app/api/auth for [...nextauth].js file

Deegan answered 5/4, 2023 at 6:39 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Typify
C
2

I'm not sure if you managed to get this fixed (please let me know if you did!) but I'm facing what I believe to be the exact same issue as yours, even so far as to have raised an issue on GitHub about it. I'll let you know what comes back, but one thing that may be worth considering is what version of NextAuth you're running.

Claraclarabella answered 22/2, 2023 at 13:47 Comment(3)
Hey @Gavin, did you fix this issue? I am still facing this issue and not able to figure out what's wrong.Totality
Hey @RishavSharma there was actually a bit of silliness going on with my issue, although I suppose it could still apply to yours or anyone else's who's reading this? Turns out our servers were configured to send any request with a path beginning /api to the actual API servers and not the web servers. This of course went a long way to explaining (and then fixing) the issue!Claraclarabella
Hey thanks, Gavin, I finally resolved it after some time but not sure what was the solution that worked in my case. Anyways, thanks again for putting in the effort to write your solution. Have great days :)Totality
E
2

I also ran into this issue, due to mismatched versions of next and next-auth - mine was outdated.

So you can try matching the versions first, and then try again.

Of course this is just the situation I encountered, I'm not sure if it applies to your case, but hopefully it helps.

I'm on "next": "13.4.3","next-auth": "^4.22.1" now, It works well.

Eagan answered 29/5, 2023 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.