Skip to content

Instantly share code, notes, and snippets.

@LawJolla
Created September 18, 2017 06:19
Show Gist options
  • Save LawJolla/db27a13348d72504e9a64d3bf8699fea to your computer and use it in GitHub Desktop.
Save LawJolla/db27a13348d72504e9a64d3bf8699fea to your computer and use it in GitHub Desktop.
Apollo + Gatsby SSR
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
])
}
@shreyas-1997
Copy link

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
image

Wrap-root-element.js
image

please bro guide me to add SSR in this project i am stuck in this part since one month

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment