Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js using apollo client cache in getServerSideProps

I'm using Next.js with apollo client. I need to create a seamless workflow between server and client side. In my ssr page, I run a query in getServerSideProps and send the created apollo cache to browser like below;

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const apolloClient = initializeApollo();

  await apolloClient.query({
    query: CitiesQuery,
    variables: {
      name: cityParamVar(),
    },
  });

  return {
    props: {
      initialApolloState: apolloClient.cache.extract(),
    },
  };
}

On the client side, I have my apollo cache already filled with query data, wonderful!. Then, I run a second query on client side, so apollo cache will have my second query results as well. Then, I navigate to Home page and then come back to my page again. Of course getServerSideProps will run again. Here, in getServerSideProps function, is it possible to obtain the same apollo cached filled with my second query results, that was run on client side?

Can we create a totally seamless workflow between client & server?

I saw samples just run const apolloClient = initializeApollo() in getServerSideProps. So, I won't have the updated cache! Am I missing something?

like image 405
killjoy Avatar asked Oct 16 '25 20:10

killjoy


1 Answers

If I understood your question correctly, there doesn't seem to be a clean way to do it at this point. I've been looking into a way to solve the same issue while using React Query.

This feature request discussion at Next.js GitHub repo should provide some useful background information. There's also a couple of hacky workarounds which you could try.

like image 55
ristomatti Avatar answered Oct 19 '25 03:10

ristomatti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!