【问题标题】:getInitialProps is called on front end in nextjs在 nextjs 的前端调用 getInitialProps
【发布时间】: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


【解决方案1】:

您分享的link 说明您需要使用getServerSideProps 而不是getInitialProps 用于Next.js 版本> 9.3。

【讨论】:

    【解决方案2】:

    由于getInitialProps 在客户端和服务器上调用,您必须为这两种情况编写身份验证逻辑。要在客户端使用 useUser 钩子获取会话,在服务器上使用 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
    }
    
        
    
        
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 2021-08-04
      • 2020-06-26
      • 2018-01-05
      • 1970-01-01
      • 2019-09-01
      • 2020-06-27
      • 2021-09-15
      相关资源
      最近更新 更多