skip to Main Content

I have code for user fetch from the session in _app.tsx.

MyApp.getInitialProps = async ({ ctx }: any) => {
  const { req, res } = ctx;

  const session = auth0.getSession(req, res)
  return { user: session?.user } 

}

Problem is, that getInitialProps is sometimes called on client-side. I don`t understand why? Documentation says:

`getInitialProps enables server-side rendering in a page and allows you to do initial data population, which means sending the page with the data already populated from the server. This is especially useful for SEO.

https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

What is wrong? Why is my function called on client-side?

In case I am wrong, how can I fetch user session data from server on server side?

2

Answers


  1. The link you shared explains you need to use getServerSideProps instead of getInitialProps for Next.js version > 9.3.

    Login or Signup to reply.
  2. Since getInitialProps called on client and server, you have to write authentication logic for both cases. To get the session on client use useUser hook, on server use getSession

    import { useUser } from '@auth0/nextjs-auth0';
    
    let user;
    if (typeof window === 'undefined'){
       const session=auth0.getSession(req,res)
       console.log("check session to get user",session)
       user=session.user
    } else {
         const data = useUser()
         user=data.user
    }
    
        
    
        
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search