Apollo HOC for Next.js.
For Next v9
use the latest version.
For Next v6-v8
use the version 3.4.0
.
For Next v5
and lower go here and use the version 1.0
.
Install the package with npm:
npm install next-with-apollo
or with yarn:
yarn add next-with-apollo
Create the HOC using a basic setup and apollo-boost:
// lib/withApollo.js
import withApollo from 'next-with-apollo';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';
export default withApollo(
({ initialState }) => {
return new ApolloClient({
uri: 'https://mysite.com/graphql',
cache: new InMemoryCache().restore(initialState || {})
});
},
{
render: ({ Page, props }) => {
return (
<ApolloProvider client={props.apollo}>
<Page {...props} />
</ApolloProvider>
);
}
}
);
Note: apollo-boost is used in this example because is the fastest way to create an
ApolloClient
, but is not required.
Note: If using
react-apollo
, you will need to import theApolloProvider
fromreact-apollo
instead of@apollo/react-hooks
.
Now let's use lib/withApollo.js
in one of our pages:
// pages/index.js
import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';
import withApollo from '../lib/withApollo';
// import { getDataFromTree } from '@apollo/react-ssr';
const QUERY = gql`
{
title
}
`;
const Index = () => {
const { loading, data } = useQuery(QUERY);
if (loading || !data) {
return <h1>loading...</h1>;
}
return <h1>{data.title}</h1>;
};
export default withApollo(Index);
// You can also override the configs for withApollo here, so if you want
// this page to have SSR (and to be a lambda) for SEO purposes and remove
// the loading state, uncomment the import at the beginning and this:
//
// export default withApollo(Index, { getDataFromTree });
Now your page can use anything from @apollo/react-hooks
or react-apollo
. If you want to add Apollo in _app
instead of per page, go to Using _app.
withApollo
receives 2 parameters, the first one is a function that returns the Apollo Client, this function receives an object with the following properties:
ctx
- This is the context object sent by Next.js to thegetInitialProps
of your page. It's only available for SSR, in the client it will beundefined
initialState
- IfgetDataFromTree
is sent, this will be the initial data required by the queries in your page, otherwise it will beundefined
headers
- This isctx.req.headers
, in the client it will beundefined
.
The second, optional parameter, received by withApollo
, is an object
with the following props:
render
- A function that receives an object ({ Page, props }
) with the currentPage
Component to be rendered, and itsprops
. It can be used to wrap your pages with<ApolloProvider>
. It's optionalgetDataFromTree
- implementation ofgetDataFromTree
, defaults toundefined
. It's recommended to never set this prop, otherwise the page will be a lambda without Automatic Static OptimizationonError
- A function that will be called ifgetDataFromTree
encounters errors. If not supplied errors will be silently ignored. It will be called with 2 parameters:error
- TheError
objectctx
- The page context (NextPageContext
)
Pages with getInitialProps
can access the Apollo Client like so:
Page.getInitialProps = ctx => {
const apolloClient = ctx.apolloClient;
};
Next.js applies very good optimizations by default, including Automatic Static Optimization, and as long as the getDataFromTree
config is not added, your pages will always be static and can be served directly from a CDN, instead of having a serverless function being executed for every new request, which is also more expensive.
If your page has getDataFromTree
to remove the loading states of Apollo Queries, you should consider handling the loading states by yourself, fetching all queries per request and before sending the initial HTML will slow down the first render, and the user may end up waiting a long time without any feedback.
If you want to add Apollo to all pages, you can use pages/_app.js
, like so:
import withApollo from 'next-with-apollo';
import { ApolloProvider } from '@apollo/react-hooks';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
const App = ({ Component, pageProps, apollo }) => (
<ApolloProvider client={apollo}>
<Component {...pageProps} />
</ApolloProvider>
);
export default withApollo(({ initialState }) => {
return new ApolloClient({
uri: 'https://mysite.com/graphql',
cache: new InMemoryCache().restore(initialState || {})
});
})(App);
It's better to add Apollo in every page instead if you have pages that don't need Apollo.
To access Apollo Client in each page's getInitialProps
, add getInitialProps
to App
like so:
import App from 'next/app';
MyApp.getInitialProps = async appContext => {
const appProps = await App.getInitialProps(appContext);
return { ...appProps };
};
If you either add the getDataFromTree
config or getInitialProps
, it will turn all pages into lambdas and disable Automatic Static Optimization.
In 4.3.0
all the queries where fetched on server by default (getDataFromTree
option was set to 'always'
by default). In order to get the same behaviour in 5.0.0
you need to explicitly pass getDataFromTree
(from @apollo/react-ssr
) to withApollo
.