0

The answers provided in this post didn't work for me, and there's been no update. Getting NextAuth.js user session in Apollo Server context

// ./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,
  };
}

I'm guessing there's a mismatch between what Next v Apollo are expecting from requests. Any ideas how to get a valid next-auth session into gql context?

2 Answers2

0

The only working solution I came across is calling the

http://localhost:3000/api/auth/session

endpoint separately and extracting the session. You can find the full version on this URL. Scroll down to the last one, by @gaganbiswas

CyberMessiah
  • 1,084
  • 11
  • 14
-1

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