Search code examples
reactjsnext.jsapolloapollo-client

Can Apollo graphql be used with Nextjs without having to install react-router-dom?


An ApolloProvider wraps an app:

<ApolloProvider client={client}>
    <App />
</ApolloProvider>

The problem is, in nextjs you can declare route components in the pages folder WITHOUT having to add them to App.js

Which leads to the error "Invariant Violation: Could not find "client" in the context or passed in as an option. "

Can Apollo be used in these components with the native Nextjs way of handling routes?


Solution

  • This is what I did with mine, make a separate folder I called it apollo folder just like this:

    enter image description here

    then inside that folder create a file name it whatever you want then put this code or whatever code for you apollo client

    apollo/ apolloClient.js

     import ApolloClient from "apollo-client";
        import { InMemoryCache } from "apollo-cache-inmemory";
        import { createHttpLink } from "apollo-link-http";
        import { ApolloProvider } from "@apollo/react-hooks";
        import { setContext } from "apollo-link-context";
        
        const httpLink = createHttpLink({
          uri: "http://localhost:5000",
        });
        
        const authLink = setContext(() => {
          const token = localStorage.getItem("jwtToken");
          return {
            headers: {
              Authorization: token ? `Bearer ${token}` : "",
            },
          };
        });
        
        const client = new ApolloClient({
          link: authLink.concat(httpLink),
          cache: new InMemoryCache(),
        });
        
        export default client;
    

    You have to export the client or what I did with mine and go to the _app.js:

    import "../styles/globals.css";
    import { ApolloProvider } from "@apollo/react-hooks";
    import client from "../apollo/apolloClient";
    
    function MyApp({ Component, pageProps }) {
      return (
        <ApolloProvider client={client}>
              <Component {...pageProps} />
        </ApolloProvider>
      );
    }
    
    export default MyApp;
    

    We have imported the client from the apolloClient.js file that we just created and exported the client

    Hope this is what you mean.