在nextjs中使用app router中的getServerSession()方法保护API路由

4ngedf3f  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(73)

使用getServerSession()方法保护API路由。

pages/api/get-session-example.js

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

export default async (req, res) => {
  const session = await 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()
}

字符串
现在如何为应用程序路由器编写相同的代码?

6ioyuze2

6ioyuze21#

只需要使用getServerSession(),不带任何参数,nextjs会自动为你完成剩下的工作。

相关问题