scx*_*992 12 reactjs next.js next-auth
我无法在 getServerSideProps 中使用 HTTPS 的 getSession() 。
\n这正常吗?我尝试了很多次。
\n如果使用 HTTPS 我会得到它。我无法在 getServerSideProps 中使用 getSession()
\n__Secure-next-auth.callback-url\n__Secure-next-auth.session-token\n__Host-next-auth.csrf-toke\nRun Code Online (Sandbox Code Playgroud)\n如果使用 HTTP 并且我可以在 getServerSideProps 中 getSession() 就可以了
\nnext-auth.callback-url\nnext-auth.session-token\nnext-auth.csrf-token\nRun Code Online (Sandbox Code Playgroud)\n如何在 getServerSideProps 中的 HTTPS getSession() 上修复它?
\n我在 http 或 https 上运行相同的代码进行测试
\n如果使用 http 运行,我可以获得 props.session\n 如果使用https运行,我无法获取 props.session
\nimport { getSession } from 'next-auth/client';\n\nexport default function Home(props) {\n console.log(props.session);\n return (\n <div>\n <h1>Server Side Rendering</h1>\n </div>\n );\n}\nexport async function getServerSideProps(context) {\n return {\n props: {\n session: await getSession(context),\n },\n };\n}\n\nRun Code Online (Sandbox Code Playgroud)\n备注\xef\xbc\x9a
\nNEXTAUTH_URL了.envgetInitialProps我需要获取 session.user.id 来获取数据库prisma,同时prisma需要在 getServerSideProps 中运行raz*_*boy 21
这种行为是正常的。这些值是 的内部值next-auth。NEXTAUTH_URL当前缀为时https,cookie 将被标记为安全。您可以在此处查看行为:
内部next-auth将处理会话,无论http或https。
要配置客户端会话,您可以按照文档中的示例进行操作:
完整的工作示例在这里:
首先配置一个提供程序以便在组件之间共享会话。
页面/_app.js
import { Provider } from "next-auth/client"
export default function App({ Component, pageProps }) {
return (
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>
)
}
Run Code Online (Sandbox Code Playgroud)
如果您还需要在服务器端渲染期间支持身份验证,那么您将需要。
页面/index.js
import { getSession } from "next-auth/client"
export async function getServerSideProps(ctx) {
return {
props: {
session: await getSession(ctx)
}
}
}
Run Code Online (Sandbox Code Playgroud)
在您的组件内部使用由提供的反应钩子next-auth
import { useSession } from "next-auth/client"
export default function Component() {
const [session, loading] = useSession()
if (session) {
return <p>Signed in as {session.user.email}</p>
}
return <a href="/api/auth/signin">Sign in</a>
}
Run Code Online (Sandbox Code Playgroud)
在服务器端的 api 路由中:
import { getSession } from "next-auth/client"
export default async (req, res) => {
const session = await getSession({ req })
res.end()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70020 次 |
| 最近记录: |