Created
September 18, 2017 06:19
-
-
Save LawJolla/db27a13348d72504e9a64d3bf8699fea to your computer and use it in GitHub Desktop.
Apollo + Gatsby SSR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { renderToString, renderToStaticMarkup } from 'react-dom/server' | |
import ApolloClient, { createNetworkInterface, } from 'apollo-client' | |
import { ApolloProvider, getDataFromTree } from 'react-apollo' | |
// Apollo Setup | |
const networkInterface = createNetworkInterface({ | |
uri: process.env.GRAPHCOOL_API | |
}) | |
// Apollo client in server side rendering mode | |
const client = new ApolloClient({ | |
ssrMode: true, | |
networkInterface, | |
dataIdFromObject: o => o.id | |
}) | |
exports.replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => { | |
return new Promise((resolve, reject) => { | |
// bodyComponent is the entire React component tree for the page | |
const ApolloQueries = ( | |
<ApolloProvider client={client}> | |
{bodyComponent} | |
</ApolloProvider> | |
); | |
// getDataFromTree walks ApolloQueries tree for all Apollo GQL queries | |
// It runs the queries and mutates client object | |
getDataFromTree(ApolloQueries) | |
.then(() => { | |
const ConnectedBody = () => ( | |
<ApolloProvider client={client}> | |
{bodyComponent} | |
</ApolloProvider> | |
) | |
// renders Connected Body to string | |
resolve(replaceBodyHTMLString(renderToString(<ConnectedBody/>))) | |
}) | |
}) | |
} | |
// function to hydrate client Apollo state | |
exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => { | |
// gets initial state with "apollo" key | |
const state = {"apollo": client.getInitialState()}; | |
// appends apollo state to the global client window object | |
const ApolloState = ( | |
<script dangerouslySetInnerHTML={{ | |
__html: `window.__APOLLO_STATE__=${JSON.stringify(state).replace(/</g, '\\u003c')};`, | |
}} | |
/> | |
); | |
setHeadComponents([ | |
ApolloState | |
]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Bro I reallly Need your i implemented the gatsby with apollo client.. it works fine for client side but i want to show all the data to server side rendereing which can be seen in view source but how can i apply SSR for apollo client and gatsby please help me..
i created a folder by name apollo inside components and inside apollo folder i create two file client.js and wraproot element.js
see the screenshot
Client.js
Wrap-root-element.js
please bro guide me to add SSR in this project i am stuck in this part since one month