0

What is the best way to make next-auth user data in session globally accessible in all pages server-side?

or do I need to manually add getServerSideProps to every page to get the session user data?

<Provider session={pageProps.session}></Provider> is in _app.js return function so do I need a hoc wrapper component for this?

I tried using getInitialProps:


function MyApp({ Component, pageProps, initialLoginStatus }) {

   console.log(initialLoginStatus);

   ....

  return (

     <React.Fragment>

          <Provider session={pageProps.session}>
             ...
          </Provider>

     </React.Fragment>

  )
}

MyApp.getInitialProps = async ( ctx ) => {

  if (typeof window === "undefined") {

    return {
      initialLoginStatus: `test`
    }

  } else {

    return {
      initialLoginStatus: `error`
    }
  }

}

but I get this error: TypeError: Cannot read property 'session' of undefined for <Provider session={pageProps.session}>

yeln
  • 462
  • 2
  • 10
  • 23

1 Answers1

2

If you don't have an "_app.js" file in the "pages" folder you have to create one by putting this inside:

import {Provider} from 'next-auth/client'

export default function App({Component, pageProps}) {
    return (
        <Provider session={pageProps.session}>
            <Component {...pageProps} />
        </Provider>
    )
}

Then in your page you have to use this to use the sessions:

import {useSession} from 'next-auth/client'

&

const [session, loading] = useSession()

And you can get the name of the user by doing for example:

session.user.name

Which would give for example in the code you provided:

import {useSession} from 'next-auth/client'

function MyApp({ Component, pageProps, initialLoginStatus }) {

   const [session, loading] = useSession()
   
   console.log(session.user.name)
   console.log(session)

   console.log(initialLoginStatus);

   ....

  return (

     <React.Fragment>

          <Provider session={pageProps.session}>
             ...
          </Provider>

     </React.Fragment>

  )
}

MyApp.getInitialProps = async ( ctx ) => {

  if (typeof window === "undefined") {

    return {
      initialLoginStatus: `test`
    }

  } else {

    return {
      initialLoginStatus: `error`
    }
  }

}
Lucas Bodin
  • 311
  • 3
  • 19
  • 1
    the issue is I getting `undefined` if I `console.log` `session.user` right after `const [ session, loading ] = useSession()`, it is `undefined`, but `client-side` `await getSession();` works – yeln May 25 '21 at 16:06
  • I expected exactly the same behavior. It is indeed missleading from the docs but it is not enough with the wrappers in _app.js. You need to activate SSR and pass down server side session. _app.js ... import { useSession, getSession } from 'next-auth/client' ... ``` // Export the `session` prop to use sessions with Server Side Rendering export async function getServerSideProps(context) { return { props: { session: await getSession(context) } } } ``` – Marc Aug 31 '21 at 07:51