实现在 NextJS 13 中的 getSession() 函数。

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

Implement getSession() in NextJS 13

问题

在上述代码中,你需要在Next.js 13中实现类似getServerSideProps的功能。以下是对该功能的翻译:

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

这段代码用于在服务器端获取用户会话信息。在Next.js 13中,可以使用以下方式实现相似的功能:

import { getSession } from 'next-auth/react'

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

这将使用getSession函数来获取用户会话信息,并将其作为session属性传递给页面组件。

英文:

I implemented nextAuth in my app and faced a glitch problem on UI, when the page is reloaded I can see Signed in as ../ Not signed in for a second till a new session is fetched. I found the solution of this problem for NextJS 12 and older, and I have some difficulties to implement it in NextJS 13 without getServerSideProps().

'use client'
import './globals.css'
import { getSession, SessionProvider } from 'next-auth/react'

export default function RootLayout({ session, children }) {
  return (
    <html lang="en">
      <head />
      <body>
        <SessionProvider session={session}>
          {children}
        </SessionProvider>
      </body>
    </html>
  )
}

How to implement this function for the code above?

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

Source: https://stackoverflow.com/a/68942471/4655668

答案1

得分: 2

getServerSession:在服务器端调用,即在API路由或getServerSideProps中,我们建议使用此函数而不是getSession来检索会话对象。当您在使用NextAuth.js与数据库时,此方法特别有用。

import { authOptions } from 'pages/api/auth/[...nextauth]'
import { getServerSession } from "next-auth/next"

export async function getServerSideProps(context) {
  const session = await getServerSession(context.req, context.res, authOptions)
//...
}
英文:

>getServerSession : When calling from server-side i.e. in API routes or in getServerSideProps, we recommend using this function instead of getSession to retrieve the session object. This method is especially useful when you are using NextAuth.js with a database.

import { authOptions } from 'pages/api/auth/[...nextauth]'
import { getServerSession } from "next-auth/next"

export async function getServerSideProps(context) {
  const session = await getServerSession(context.req, context.res, authOptions)
//...
}

huangapple
  • 本文由 发表于 2023年2月14日 08:16:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442359.html
匿名

发表评论

匿名网友

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

确定