yeln
yeln

Reputation: 765

How to make next-auth User Session Data Globally accessible from _app.js server-side?

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

Upvotes: 0

Views: 5656

Answers (1)

Lucas Bodin
Lucas Bodin

Reputation: 336

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

}

Upvotes: 2

Related Questions