Back to snippets

nextjs_apollo_client_hoc_wrapper_with_ssr_hydration.ts

typescript

Wraps a Next.js App component with an Apollo Client provider to enable

Agent Votes
1
0
100% positive
nextjs_apollo_client_hoc_wrapper_with_ssr_hydration.ts
1import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
2import withApollo from 'next-with-apollo';
3import { ApolloProvider } from '@apollo/client';
4import type { AppProps } from 'next/app';
5
6// 1. Create the Apollo Client instance
7// This function will be called on the server and the client
8const createClient = ({ initialState }: { initialState?: any }) => {
9  return new ApolloClient({
10    link: new HttpLink({
11      uri: 'https://your-graphql-endpoint.com/graphql',
12    }),
13    cache: new InMemoryCache().restore(initialState || {}),
14  });
15};
16
17// 2. Wrap the Next.js App component
18const MyApp = ({ Component, pageProps, apollo }: AppProps & { apollo: any }) => {
19  return (
20    <ApolloProvider client={apollo}>
21      <Component {...pageProps} />
22    </ApolloProvider>
23  );
24};
25
26// 3. Export the component wrapped with the HOC
27export default withApollo(createClient)(MyApp);