next-ssr-with-apollo
v1.1.0
Published
Opinionated HOC to integrate Apollo into an SSR Next.js app
Downloads
2
Readme
next-ssr-with-apollo
Opinionated HOC to integrate Apollo into an SSR Next.js app
Features
- Allow child components to declare their own data dependencies. (None of the prop-drilling from getServerSideProps examples.)
- Support data dependencies in any component, including components used in App layout. (Note this uses App getInitialProps and opts-out of any pages in the app being static.)
- Prefetch data before displaying new route on client-side navigation, same as server-side navigation. (Avoid displaying next page in a loading state.)
- Simplified caching model: Start fresh when navigating to new route.
(Don't worry about so much about
fetchPolicy
,nextFetchPolicy
, manually refetching queries, or the unpredictabile side-effects of these features.
Installation
Inside your Next.js project:
npm install graphql @apollo/client next-ssr-with-apollo
Usage
Wrap your App component to provide apollo client for your entire app.
pages/App.tsx
import type { AppProps } from "next/app";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { createWithApollo } from "next-ssr-with-apollo";
const withApollo = createWithApollo({
client() {
return new ApolloClient({
uri: "https://rickandmortyapi.graphcdn.app/",
cache: new InMemoryCache(),
});
},
});
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default withApollo(MyApp);
Now you can use apollo hooks in any component in your app, and queries will be prefetched before a route is shown.
Queries with the ssr: false
option won't be prefetched (server-side or client-side).
They will initially be in a loading state when the route is shown.
Options
client
The client
factory, where you define your Apollo Client, is invoked:
- on server: once per request
- on client: once per page load and once per client-side navigation
The client
factory receives some params:
headers
- HTTP request headers. Only defined on server side.
Example
const withApollo = createWithApollo({
client({ headers }) {
const isServer = typeof window === "undefined";
const baseUri = isServer ? "http://127.0.0.1:3000" : "";
return new ApolloClient({
uri: `${baseUri}/api/graphql`,
headers:
isServer && headers!.authorization
? { authorization: headers!.authorization }
: {},
cache: new InMemoryCache(),
});
},
});