Sending user credentials when used in Next 13's app dir/react server components

We’re using Auth0 so in the graphql server, we’re doing this:

export default createYoga<{
  req: NextApiRequest
  res: NextApiResponse
}>({
  context: async function createContext({ req, res }: { req: NextApiRequest; res: NextApiResponse }) {
    const session = await getSession(req, res)

    // If the user is not logged in, return an empty object
    if (!session) {
      return
    }

    return { session }
  },
  schema,
  // Needed to be defined explicitly because our endpoint lives at a different path other than `/graphql`
  graphqlEndpoint: '/api/graphql'
})

The issue is that because ApolloClient is running as a server a component (the default in Next 13’s app directory) it’s not passing whatever cookies/etc even when credentials: 'include' is set. I assume it’s because it’s running on the server and it doesn’t have access to the user info.

On our page, we query like this:

const Dashboard = async (): Promise<JSX.Element> => {
  const client = getClient()
  const { data } = await client.query({ query })

  return (
    <main>
      <h2 className='font-title'>Dashboard</h2>
      <p>{data.greetings}</p>
    </main>
  )
}

And per the blog article, our apollo client code is here:

import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'

type Client = ApolloClient<any>

let client: Client | null = null

const httpLink = new HttpLink({
  uri: 'http://localhost:3000/api/graphql'
})

export const getClient = (): Client => {
  /* Create a new client if there's no existing one
     or if we are running on the server. */
  if (!client || typeof window === 'undefined') {
    client = new ApolloClient({
      link: httpLink,
      cache: new InMemoryCache(),
      credentials: 'include'
    })
  }

  return client
}

I’ll have to a) do some digging to see which headers/user cookie data need to be sent and b) how to send that using apolloclient, unless what I’ve posted here changes your suggestion

1 Like