【发布时间】:2021-04-24 06:48:52
【问题描述】:
我的网络应用正在使用:
- NextJS
- 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" });
问题是,会话 (userSession) 始终为空,即使我已登录(并且可以从适当的 NextJS API 路由中很好地获取会话)。我的猜测是,因为用于获取会话的 NextAuth 函数,getSession({ req }) 正在传递 req——这是由 Apollo Server Micro 提供的,而不是来自 NextJS(NextAuth 所期望的)。我做了很多搜索,找不到遇到同样问题的人。非常感谢任何帮助!
【问题讨论】:
-
如果有人在使用 Auth0 + graphql 时发生这种情况: import { getSession } from '@auth0/nextjs-auth0' context: async args => { const session = await getSession(args.req) return { 用户: session.user } }
-
那么也许您尝试不将
req作为对象传递,而是直接传递?const userSession = await getSession( req )
标签: graphql next.js apollo-server next-auth