在Next.js 13 Beta的应用程序目录中,如何使用next-auth getServerSession在服务端组件中?

17
我正在使用next auth v4与next js 13 beta和服务器组件,一切都运行良好。但是我有一个情况,需要知道已登录用户的ID,因为我正在使用next auth,我可以访问会话,我可以使用useSession(),但是那样我将需要将组件变成客户端组件,所以我想在服务器上使用它,在API中我可以使用getServerSession,因为我可以访问req和res对象,但是在next js beta中,由于新的应用程序目录,我无法这样做。如果您知道如何解决此问题,请告诉我。谢谢。
import { getServerSession } from "next-auth";
import { authOptions } from "@/pages/api/auth/[...nextauth]";

const Test = async () => {
    const user_id = 1; // How do I get user id from session, user_id is available in session

    // I don't have access req & res object in server component.
    const data = await getServerSession(request, response, authOptions);

    console.log(data);

});
    return (
        <></>
    );
};

export default Test;

未找到足够的信息

3个回答

19

我找到了一个答案,在下一个js 13 beta版本中,您将不需要使用request和response对象,只需使用authOptions即可,它将起作用。

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

const Test = async () => {

    const data = await getServerSession(authOptions);

    console.log(data);

});
    return (
        <></>
    );
};

export default Test;

1
能否分享一下你的authOptions? - Grayson Langford
1
请查看此链接:[https://gist.github.com/shakibhasan09/c37eb67910a992f881e722313531b2fb] - Shakib Hasan
1
[https://gist.github.com/shakibhasan09/c37eb67910a992f881e722313531b2fb] - Shakib Hasan
1
另一个404 - 请您在帖子中分享您的authOptions,可以吗? - David Conlisk
1
这会在服务器控制台中显示一条消息。不确定它是否为一个警告:“getServerSession” 在 React 服务器组件中使用。 - mayid
显示剩余2条评论

5

选项文档

import { NextAuthOptions } from 'next-auth'
import { getServerSession } from 'next-auth'

这是NextAuthOptions类型
export interface AuthOptions {
  providers: Provider[];
  secret?: string;
  session?: Partial<SessionOptions>;
  jwt?: Partial<JWTOptions>;
  pages?: Partial<PagesOptions>;
  callbacks?: Partial<CallbacksOptions>;
  events?: Partial<EventCallbacks>;
  adapter?: Adapter;
  debug?: boolean;
  logger?: Partial<LoggerInstance>;
  theme?: Theme;
  useSecureCookies?: boolean;
  cookies?: Partial<CookiesOptions>;
}

这是如何获取会话的方法
const session = await getServerSession(authOptions)

基于AuthOptions接口
const authOption: NextAuthOptions = {
  // Since you tagged prisma
  adapter: PrismaAdapter(yourDbConfig),
  session: {
    strategy: 'jwt',
  },
  // https://next-auth.js.org/configuration/pages
  pages: {
    signIn: '/login',
  },
  providers: [
    GoogleProvider({
      clientId: clientId,
      clientSecret: clientSecret,
    }),
  ],
  callbacks: {
    async session({ token, session }) {
      if (token) {
        // set session here
      }
      return session
    },
    async jwt({ token, user }) {
      const dbUser = getUserByTokenEmail

      //add logic here
    },
    
  },
}

这是我们如何使用authOptions来设置next-auth。
// app/auth/[...nextauth].ts (I htink after next 13.2)
// pages/api/auth/[...nextauth].ts before

import { authOptions } from 'folderLocationOfauthOptions'
import NextAuth from 'next-auth'


export default NextAuth(authOptions)

1
哦,谢谢,非常详细。虽然,刚开始所有这些,文件结构让我有点头疼。如果我们要迁移离开 /pages/api/auth/[...nextauth].js,那么这些配置和函数应该放在哪里? - mtro
@mtro 这正是我目前也在努力理解的问题。有什么进展吗? - Laky
@mtro 这正是我目前也在努力理解的问题。有什么进展吗? - undefined
@Laky我们不会迁移 [...nextauth].js。已更新答案。 - Yilmaz
@Laky我们不会迁移 [...nextauth].js。已更新答案。 - undefined

1
如果你想用应用程序路由器做同样的事情,流程是一样的,只是将authOptions添加到app/api/auth/[...nextauth]/route.(ts/js)中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接