Search code examples
reactjsapollo-clientnext.js13app-router

Using apollo client with nextjs 13 with app router


I was planning to upgrade to nextJS 13 with app router. But I'm not able to make apollo client work with the latest version. Creating a single cache for server components will leads to data leaks as apollo was designed with single user in mind. I found an experimental library(https://github.com/apollographql/apollo-client-nextjs) but I'm not confident enough to use an experimental lib in my project

To prevent data leaks I could create a new in memoryCache if i'm on server every time. But I'm not able to make it work as well.

const getClient = ()=>{
    if(!client || typeof window==="undefined"){
        client = new ApolloClient({
            link:new HttpLink({
                uri:"https://graph.staging.strollby.com/graphql",
            }),
            cache: new InMemoryCache(),
        });
    }
    return client
}

https://github.com/apollographql/apollo-client-nextjs, this library seems the right solution, but unfortunately.

This package is experimental. Generally it should work well, you might run into race conditions when your Client Component is still rendering in SSR, and already making overlapping queries on the browser. This cannot be addressed from our side, but would need API changes in Next.js or React itself. If you do not use suspense in your application, this will not be a problem to you.


Solution

  • As you can read in that warning message, those potential race conditions are the only problem, and they are a Next.js problem, not a problem with the experimental library itself.

    I might add: they are extremely rare - they would require a very long SSR run while a part of your application already started browser-side and fetches "newer" data through user interaction (e.g. the user deletes something in the browser while the server still renders with that item in the cache).

    You can read more about this in this (slightly outdated) document: RFC for the Apollo Next.js story.

    If you want to only do RSC, and never fetch anything with suspense in client components, that is even completely eliminated, as that warning applies to React's "streaming SSR" only, where the browser already starts running while the server is still doing SSR.

    All that said: this is a shortcoming of Next (transporting values over too late) and you will encounter that with any client-side fetching library you might use for suspense in client components, until Next gets a better primitive in place. There is no way anyone could implement something better in userland, unless they were to fix Next.js itself. So as long as you plan to use the App Router, that library is your best choice.

    It's probably more stable than the App Router itself, me as an author of that library and Vercel just have different opinions on what to call "stable".