getServerSession 在 Next.js 13 中与应用目录下的 API 路由

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

getServerSession on next js 13 with api routes on app directory

问题

我正在使用next-auth并尝试在服务器组件中获取serverSession在Next.js 13 beta中使用App目录并且API目录也在App目录中所以根据next-auth文档我可以这样获取serverSession

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

export default async function Page() {
  const session = await getServerSession(authOptions)
  return <pre>{JSON.stringify(session, null, 2)}</pre>
}

但是AuthOptions不可用,因为根据next-auth文档,我的API路由应该像下面这样在next.js 13 beta中看起来:

import NextAuth from "next-auth"

const handler = NextAuth({
  ...
})

export { handler as GET, handler as POST }

所以没有authOptions可供导入,就像请求一样。我该怎么做?

谢谢


<details>
<summary>英文:</summary>

Im using next-auth and trying to get serverSession on server component, im using Next.js 13 beta with App directory and the API directory is also on the App directory so according to next-auth docs this is how I can get the serverSession

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

export default async function Page() {
const session = await getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre>
}


but the AuthOptions is not available because according to next-auth docs again this is how my api route should looks like with next.js 13 beta

import NextAuth from "next-auth"

const handler = NextAuth({
...
})

export { handler as GET, handler as POST }


so there is no authOptions to import like the request

how can I do that

Thanks

</details>


# 答案1
**得分**: 4

以下是要翻译的内容:

您可以按照以下方式简单导出 authOptions 和 handlers:

```typescript
export const authOptions = {
   //...
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
英文:

You can simply export authOptions and handlers following this way:

export const authOptions = {
   //...
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

huangapple
  • 本文由 发表于 2023年4月20日 06:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059272.html
匿名

发表评论

匿名网友

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

确定