Next Auth getSession 在 api 路由中不起作用

Ant*_*nio 5 api reactjs next.js next-auth

所以基本上我使用 getServerSideProps 来调用一些 API。当我在 getServerSideProps() 中调用 getSession 时,我得到一个有效的对象。

export async function getServerSideProps({ req }) {
   const session = await getSession({ req }); // works
Run Code Online (Sandbox Code Playgroud)

但是当我在 getServerSideProps() 函数中调用的 API 中调用它时,我得到 null。

import { getSession } from "next-auth/react";

export default async (req, res) => {
  const { db } = await connectToDatabase();

  const session = await getSession({ req }); // returns null
Run Code Online (Sandbox Code Playgroud)

这是 NextAuth 文档供参考:

在此输入图像描述

lan*_*ion 4

虽然已经很晚了,但我在文档中找到了可以在节中获取 API 中适当的会话对象的部分。

  1. 使用unstable_getServerSession()
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"

export default async (req, res) => {
  const session = await unstable_getServerSession(req, res, authOptions)
  if (session) {
    // Signed in
    console.log("Session", JSON.stringify(session, null, 2))
  } else {
    // Not Signed in
    res.status(401)
  }
  res.end()
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用 getToken()
// This is an example of how to read a JSON Web Token from an API route
import { getToken } from "next-auth/jwt"

export default async (req, res) => {
  // If you don't have NEXTAUTH_SECRET set, you will have to pass your secret as `secret` to `getToken`
  const token = await getToken({ req })
  if (token) {
    // Signed in
    console.log("JSON Web Token", JSON.stringify(token, null, 2))
  } else {
    // Not Signed in
    res.status(401)
  }
  res.end()
}
Run Code Online (Sandbox Code Playgroud)

最重要的部分是通过authOptions导入的/api/[...nextauth]

注意:getSession是一个客户端 API,因为它仅适用于getStaticProps