【发布时间】:2022-01-11 08:46:47
【问题描述】:
使用React.js 和React-Auth 时,调用getServerSideProps 等服务器端函数将阻止您通过next export 导出项目。这是我的pages/_app.js 的内容,我从文档中复制了结构(https://next-auth.js.org/getting-started/client 和https://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()返回一个包含两个值的对象:data和status"。它不返回loading属性。
标签: javascript node.js next.js next-auth