What is the best way to pass session data from a Client component to a server component in NEXT.js 13>?

huangapple go评论73阅读模式
英文:

What is the best way to pass session data from a Client component to a server component in NEXT.js 13>?

问题

我正在开发一个 Web 应用程序,在其中我需要将 session?.user?.emailnext-auth/reactuseSession() 传递给服务器端组件,该组件执行了一个到 /api/users/email/ 的 fetch 请求,以查找是否存在具有该特定电子邮件地址的用户。

阅读文档后,我意识到不应该在包含我的 useSession()'use client' 组件内使用服务器组件。

如何最好地构建这个结构?

英文:

I am developing a web app where I need to pass session?.user?.email from useSession() in next-auth/react to a sever side component where it carries out a fetch request to /api/users/email/ to find out if a user exists with that particular email address.

After reading the documentation, I realised that you are not supposed to use server components inside 'use client' components where I have my useSession()

What is the best way to structure this?

答案1

得分: 0

你可以使用 getServerSession 方法直接在服务器组件上获取它:

export default async function ServerComponent() {
const session = getServerSession(authOptions) // 在某处定义的认证选项以供处理

return <> {session?.user.email} </>
}

我想,根据这里的说明,使用客户端上的 useSession 会导致额外的请求:
"由于 Next.js 处理 getServerSidePropsgetInitialProps 的方式,每次加载受保护的页面都必须进行服务器端请求以检查会话是否有效,然后生成所请求的页面(SSR)。这会增加服务器负载,如果您可以接受从客户端发出请求,还有一种替代方法。您可以使用 useSession 的方式,确保您始终拥有有效的会话。如果在初始加载状态后找不到会话,您可以定义适当的响应操作。"

因此,也许考虑在服务器上获取它,然后在需要时传递给客户端。

英文:

You can use getServerSession method to get it on server component directly:

export default async function ServerComponent() {
const session = getServerSession(authOptions) // auth options you defined somewhere to consume with handler

return <> {session?.user.email} </>
}

I suppose using useSession on client makes additional requests as stated here link:
Due to the way Next.js handles getServerSideProps and getInitialProps, every protected page load has to make a server-side request to check if the session is valid and then generate the requested page (SSR). This increases server load, and if you are good with making the requests from the client, there is an alternative. You can use useSession in a way that makes sure you always have a valid session. If after the initial loading state there was no session found, you can define the appropriate action to respond.

So maybe reconsider getting it on server and then passing to client when needed

huangapple
  • 本文由 发表于 2023年5月21日 12:56:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定