【问题标题】:Next-Auth: Make Session Available In _app.js Without getServerSidePropsNext-Auth:在没有 getServerSideProps 的 _app.js 中使会话可用
【发布时间】:2022-01-11 08:46:47
【问题描述】:

使用React.jsReact-Auth 时,调用getServerSideProps 等服务器端函数将阻止您通过next export 导出项目。这是我的pages/_app.js 的内容,我从文档中复制了结构(https://next-auth.js.org/getting-started/clienthttps://github.com/nextauthjs/next-auth/issues/1210#issuecomment-782630909):

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    console.log(session), // -> undefined in server- and client-console
    <SessionProvider session={session}>
      {Component.auth ? (
        <Auth>
          <Component {...pageProps} />
        </Auth>
      ) : (
        <Component {...pageProps} />
      )}
    </SessionProvider>
  )
}

function Auth({ children }) {
  const { data: session, status, loading } = useSession({required: true})
  const isUser = !!session?.user 
  console.log(session)// -> undefined in server- but correct in client-console
  React.useEffect(() => {
      if (loading) return   // Do nothing while loading
      if (!isUser) signIn()
  }, [isUser, loading])

  if (isUser) {
    return children
  }

  // Session is being fetched, or no user.
  // If no user, useEffect() will redirect.
  return <div>Loading...</div>
}

这里的问题是session 在服务器端总是undefined。每次成功登录后,在我的回调将我带到所需的受保护页面后,我都会被重定向到signIn-页面。但是,我认为 useEffect 只会在客户端运行 - 因此我不确定为什么我会重定向到 signIn()

但是,请考虑以下文件pages/index.js

export default function Index() {
  const {data: session} = useSession();
  console.log(session); // -> will return actual session
  // session is always non-null inside this page, all the way down the React tree.
  return "Some super secret dashboard"
}

Index.auth = false // For testing, to avoid redirect to signIn

在这里,我可以毫无问题地阅读会话(即使会话似乎一直在重新创建)。看来我必须想办法将会话数据推送到pageProps。否则每次(成功)登录后我都会被重定向到登录页面。

如果我将以下代码添加到pages/index.js(它在page/_app.js 内部不起作用),则会话数据已正确添加到pages/_app.js 中的pageProps

export async function getServerSideProps(ctx) {
  return {
    props: {
      session: await getSession(ctx)
    }
  }
}

在不使用像getServerSideProps 这样的任何服务器端函数的情况下,将session 添加到pages/_app.js 中的pageProps 的最佳方法是什么?

【问题讨论】:

  • docs: "useSession() 返回一个包含两个值的对象:datastatus"。它不返回 loading 属性。

标签: javascript node.js next.js next-auth


【解决方案1】:

useEffect-Hook 实际上有问题:

React.useEffect(() => {
    if (loading) return   // Do nothing while loading
    if (!isUser) signIn()
}, [isUser, loading])

loading 没有说实话。我修改了这样的块:

React.useEffect(() => {
    if (status === 'loading') return   // Do nothing while loading
    if (!isUser) signIn()
}, [isUser, status])

SignIn 现在可以正常工作了。

【讨论】:

    猜你喜欢
    • 2022-12-25
    • 2021-08-17
    • 2021-10-26
    • 2022-12-11
    • 1970-01-01
    • 2022-12-04
    • 2021-10-26
    • 2021-12-04
    • 2021-10-19
    相关资源
    最近更新 更多