在 Apollo Server 上下文中获取 NextAuth.js 用户会话

Nol*_*n P 4 graphql apollo-server next.js next-auth

我的网络应用程序正在使用:

  • 下一个JS
  • NextAuth.js
  • 阿波罗服务器

我在我的应用程序中设置了 NextAuth,我可以正常登录。

问题来自试图在 Apollo 上下文中访问用户的会话。我想将我的用户会话传递给每个解析器。这是我当前的代码:

import { ApolloServer, AuthenticationError } from "apollo-server-micro";
import schema from "./schema";
import mongoose from "mongoose";
import dataloaders from "./dataloaders";
import { getSession } from "next-auth/client";

let db;

const apolloServer = new ApolloServer({
  schema,
  context: async ({ req }) => {
    /*
    ...

    database connection setup
    
    ...
    */

    // get user's session
    const userSession = await getSession({ req });
    console.log("USER SESSION", userSession); // <-- userSession is ALWAYS null


    if (!userSession) {
      throw new AuthenticationError("User is not logged in.");
    }

    return { db, dataloaders, userSession };
  },
});

export const config = {
  api: {
    bodyParser: false,
  },
};

export default apolloServer.createHandler({ path: "/api/graphql" });
Run Code Online (Sandbox Code Playgroud)

问题是,会话 ( userSession) 始终为空,即使我已登录(并且可以从适当的 NextJS API 路由中获取会话)。我的猜测是,因为用于获取会话的 NextAuth 函数getSession({ req })正在被传递——这req是由 Apollo Server Micro 提供的,而不是来自 NextJS(NextAuth 所期望的)。我已经做了很多搜索,但找不到任何遇到同样问题的人。任何帮助深表感谢!

小智 7

我遇到了这个问题,我发现这是因为 Apollo GraphQL 游乐场。

没有 .playground 不会发送凭据"request.credentials": "include"

我的 NextAuth / GraphQL API 如下所示:

import { ApolloServer } from "apollo-server-micro";
import { getSession } from "next-auth/client";
import { typeDefs, resolvers } "./defined-elsewhere"

const apolloServer = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req }) => {
    const session = await getSession({ req });
    return { session };
  },
  playground: {
    settings: {
      "editor.theme": "light",
      "request.credentials": "include",
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

希望这对你有用!


J.W*_*lfe 1

我刚刚遇到类似的事情。我不是 100% 确定,因为很难知道确切的细节,因为上面的示例代码没有显示在会话为空之前您如何与客户端的 apollo 进行交互。然而,我相信您可能正在从内部进行 API 调用,这会导致静态代码生成并在构建时getStaticProps运行- 即当可能不存在这样的用户上下文/会话时。

请参阅https://github.com/nextauthjs/next-auth/issues/383

The getStaticProps method in Next.js is only for build time page generation (e.g. for generating static pages from a headless CMS) and cannot be used for user specific data such as sessions or CSRF Tokens.

另外,我不确定为什么你被否决了——在我看来,这似乎是一个合法的问题,即使答案主要是标准的 rtm :)。我以前也遇到过这种情况——你赢了一些,你输了一些:)干杯