Search code examples
reactjscachingviteserver-side-renderingapollo

How to force Apollo Client to respect 'network-only' fetchPolicy when ssrMode is set to true?


I'm using Apollo client to fetch data during SSR.

When I pass {ssrMode: true} in the client option, Apollo Client only fetches the initial request during server side rendering and serves any future request directly from the cache until I restart the server.

This issue behaves differently if {ssrMode} is omitted during Serverside Rendering. Then Apollo executes the query again, but when using useSuspenseQuery it does not suspend until the serverside cache is ready, serving a a stale cache which causes a hydration error.

I need the serverside request made with useSuspenseQuery to always fetch from network or at least respect the fetchPolicy passed to useSuspenseQuery

Suppose a client mutates data after the page has loaded. How can I make sure the serverside request does an actual request and does not serve cached data?

Do I manually need to clear the cache on the server before a request is made?


Solution

  • Apollo Client is not meant to have one long-running cache instance during SSR.

    You should create a new ApolloClient and InMemoryCache instance for every new incoming request. Otherwise you run the risk of leaking sensitive user data between different requests.

    That also means that this question will not be relevant anymore - if you always start with a new empty cache, it will always make network requests.

    All that said, ssrMode is meant for renderToString SSR, and useSuspenseQuery probably doesn't work well with it.
    As mentioned in your other question, I'd really want to encourage you to wait for the official streaming support to be released in a week or two (or build the package yourself from source right now), streaming SSR is extremely complicated to support with a data fetching library, so I wouldn't recommend to roll your own solution.