【发布时间】:2022-03-11 11:56:32
【问题描述】:
我有代码用于从_app.tsx 的会话中获取用户。
MyApp.getInitialProps = async ({ ctx }: any) => {
const { req, res } = ctx;
const session = auth0.getSession(req, res)
return { user: session?.user }
}
问题是,getInitialProps 有时会在客户端调用。我不明白为什么?文档说:
`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
怎么了?为什么我的函数在客户端被调用?
如果我错了,如何从服务器端的服务器获取用户会话数据?
【问题讨论】:
-
是的,因为 getInitialProps 与 getServerSideProps 相同,它会调用每个请求,但不是在客户端,而是在服务器端。
-
如果您继续阅读,您还会注意到以下内容:“对于初始页面加载,
getInitialProps将仅在服务器上运行。getInitialProps然后将在客户端通过next/link组件或使用next/router" 导航到不同的路线时。改用getServerSideProps仅在服务器上调用它。
标签: authentication next.js server-side-rendering auth0