Access NextAuth Session from Apollo Server

Viewed 19

I have a Next.JS app using Apollo Client on the frontend and Apollo Server on the backend. When initializing the ApolloServer instance, I'm attempting to retrieve the NextAuth session using unstable_getServerSession and add it to the context in order to access authentication details (i.e. username) in my resolvers. The return value of unstable_getServerSession is always null, but I've confirmed that a user is logged in and the session cookie is set.

Here is the relevant Apollo server initialization code from pages/api/graphql.ts

const apolloServer = new ApolloServer({
  schema,
  context: async ({ req, res }) => {
    const session = await unstable_getServerSession(req, res, nextAuthOptions);
    return {
      req,
      res,
      prisma,
      session,
    };
  },
});

let apolloServerHandler: NextApiHandler;

async function getApolloServerHandler() {
  if (!apolloServerHandler) {
    await apolloServer.start();

    apolloServerHandler = apolloServer.createHandler({
      path: "/api/graphql",
    });
  }

  return apolloServerHandler;
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const apolloServerHandler = await getApolloServerHandler();

  if (req.method === "OPTIONS") {
    res.end();
    return;
  }

  return apolloServerHandler(req, res);
}

And here is the Apollo client definition:

const httpLink = new HttpLink({
  uri: "http://localhost:3000/api/graphql",
  credentials: "same-origin",
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

Is this the recommended pattern for passing authentication details to the backend? I came across this GitHub issue that suggests adding an authentication link to the Apollo Client that adds an auth header with the token, but that only seems relevant if the backend isn't using Next.js.

Additionally, I confirmed that I'm able to access the session when using a standard API-route in Next (see example below):

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await unstable_getServerSession(req, res, nextAuthOptions);

  if (!session) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  return res.status(200).json({ message: "Success" });
}
0 Answers
Related