0
votes

I'm using Next.js 9.3.5 with Apollo and GraphQL for an SSR project I'm working on. I've implemented this example provided in the official pages:

https://github.com/vercel/next.js/blob/canary/examples/with-apollo/lib/apollo.js

So my page looks like this:

import { withApollo } from '../apollo/withApollo';

const Collections = (props) => {
   // ...
}

export const getServerSideProps = async ({ apolloClient }) => {
  console.log(apolloClient); // returns undefined

  return {
    props: {},
  };
};

export default withApollo()(Collections);

Problem is that apolloClient is not available inside getServerSideProps. But if I use getInitialProps, then it's working. The official Next.js doc says that we should be using getServerSideProps.

If you're using Next.js 9.3 or newer, we recommend that you use getStaticProps or getServerSideProps instead of getInitialProps.

Any ideas?

1
Have you added apolloClient to NextPageContext and NextAppContext? - DedaDev
Do I have to do it manually? I'm still really new to next. How do I do that? I can't seem to find anything about it. - Norbert
I've never done apollo + next neither, but context object by default doesn't have apolloClient prop, take look at this github.com/vercel/next.js/issues/9542#issuecomment-592187560 - DedaDev
Can't figure it out ... I also tried replacing getInitialProps with getServerSideProps inside withApollo, but can't do that either: getServerSideProps can not be attached to a page's component - Norbert
Hey Norbert, any solution for this? - Leafyshark

1 Answers

1
votes

I just use this and call in anywhere to get access to client in getServerSideProps

 export async function getStandaloneApolloClient() {
        const { ApolloClient, InMemoryCache, HttpLink } = await import(
            "@apollo/client"
            );
        return new ApolloClient({
            link: new HttpLink({
                uri: process.env.BASE_URL,
                fetch
            }),
            cache: new InMemoryCache()
        });
    }