Ask Question

How can I reuse the Context when using apollo-link-schema for server-side-rendering?

I am struggling when I want to use apollo-link-schema for Server Side Rendering, because the context in my resolver functions is undefined when they are called. Therefore I cannot resolve stuff from my database, because therefore I need the dataSources from the context of the ApolloServer.

Somehow it is strange, that it is required to put the context to the schema link again, basically I just want to call my "ApolloServer", which is configured with all needed contexts, from within the same server.

I couldn't find much about this topic, can someone pls help me achieving Server Side Rendering with accessing the ApolloServer Context in my resolver functions when using apollo-link-schema?

Thanks and Cheers!

ApolloGraphQLserver-side-renderingNextJS

1460 views

Authorยดs Dominik Sumer image

Dominik Sumer

โค๏ธ
1
Last edited on

1 Answer available

Best answer

Sadly I still couldn't find a satisfying solution for this problem. My best solution for now is to swap the apollo-link-schema with apollo-link-http and calling the ApolloServer with the absolute url (localhost).

As I said I am not happy with it, because now an extra http request has to be made on the server which is theoretically not necessary, but that's currently the "best" solution I could find. If someone has a better solution, would be nice if you can share it. :)

Here you can see my code snippet where I distinguish between Client and Server Side Rendering:

function createIsomorphLink(ctx) {
  if (ctx) {
    const { HttpLink } = require('@apollo/client');
    // TODO: we need to look into this, as with this we are still doing a network request to our own application, but with apollo-link-schema we don't have our context available on the serverside
    return new HttpLink({
      uri: 'http://localhost:3000/api/graphql',
      credentials: 'same-origin',
      fetch,
      headers: ctx.req && {
        cookie: ctx.req.header('Cookie'),
      },
    });
  } else {
    const { HttpLink } = require('@apollo/client');
    return new HttpLink({
      uri: '/api/graphql',
      credentials: 'same-origin',
      fetch,
    });
  }
}
๐Ÿ‘
1