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
The link you shared explains you need to use
getServerSideProps
instead ofgetInitialProps
for Next.js version > 9.3.Since
getInitialProps
called on client and server, you have to write authentication logic for both cases. To get the session on client useuseUser
hook, on server usegetSession