title: Access NextAuth Session from Apollo Server
body: <p>I have a Next.JS app using Apollo Client on the frontend and Apollo Server on the backend.
  When initializing the <code>ApolloServer</code> instance, I'm attempting to retrieve the NextAuth session using <code>unstable_getServerSession</code> and add it to the context in order to access authentication details (i.e. username) in my resolvers. The return value of <code>unstable_getServerSession</code> is always <code>null</code>, but I've confirmed that a user is logged in and the session cookie is set.</p>
  <p>Here is the relevant Apollo server initialization code from <code>pages/api/graphql.ts</code></p>
  <pre class="lang-js prettyprint-override"><code>const apolloServer = new ApolloServer({
    schema,
    context: async ({ req, res }) =&gt; {
      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: &quot;/api/graphql&quot;,
      });
    }
  
    return apolloServerHandler;
  }
  
  export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
  ) {
    const apolloServerHandler = await getApolloServerHandler();
  
    if (req.method === &quot;OPTIONS&quot;) {
      res.end();
      return;
    }
  
    return apolloServerHandler(req, res);
  }
  
  </code></pre>
  <p>And here is the Apollo client definition:</p>
  <pre class="lang-js prettyprint-override"><code>const httpLink = new HttpLink({
    uri: &quot;http://localhost:3000/api/graphql&quot;,
    credentials: &quot;same-origin&quot;,
  });
  
  const client = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache(),
  });
  
  </code></pre>
  <p>Is this the recommended pattern for passing authentication details to the backend? I came across <a href="https://github.com/nextauthjs/next-auth/discussions/1492" rel="nofollow noreferrer">this</a> 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.</p>
  <p>Additionally, I confirmed that I'm able to access the session when using a standard API-route in Next (see example below):</p>
  <pre class="lang-js prettyprint-override"><code>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: &quot;Unauthorized&quot; });
    }
  
    return res.status(200).json({ message: &quot;Success&quot; });
  }
  </code></pre>