首页 > 解决方案 > 在 gql 上下文中获取下一个身份验证用户会话时遇到问题

问题描述

这篇文章中提供的答案对我不起作用,并且没有更新。 在 Apollo Server 上下文中获取 NextAuth.js 用户会话

// ./graphql/context.ts
/**
 * Populates a context object for use in resolvers.
 * If there is a valid session from next-auth, find the user and add them to context
 * @param context context from apollo server
 */
type ApolloApiContext = ApolloContext < {
  req: IncomingMessage
} > ;
export async function createContext(context: ApolloApiContext): Promise < Context > {
  const session = await getSession(context); // ALWAYS null
  let user: User | null = null;
  if (session?.user?.email) {
    user = await prisma.user.findUnique({ where: { email: session.user.email } });
   }
  return {
    db: prisma,
    prisma,
    user,
  };
}

我猜 Next v Apollo 对请求的期望不匹配。任何想法如何将有效的下一个身份验证会话放入 gql 上下文?

标签: graphqlapollo-clientnext-auth

解决方案


const session = await getSession({ req: context.req });


推荐阅读