graphql-hooks-ssr
Server-side rendering utils for graphql-hooks
Install
npm install graphql-hooks-ssr
or
yarn add graphql-hooks-ssr
Quick Start
The below example is for fastify
but the same principles apply for express
& hapi
.
const { GraphQLClient, ClientContext } = require('graphql-hooks')
const memCache = require('graphql-hooks-memcache')
const { getInitialState } = require('graphql-hooks-ssr')
const { ServerLocation } = require('@reach/router')
const fetch = require('isomorphic-unfetch')
app.get('/', async (req, reply) => {
const client = new GraphQLClient({
url: 'https://domain.com/graphql',
cache: memCache(),
fetch
})
const App = (
<ClientContext.Provider value={client}>
<ServerLocation url={req.raw.url}>
{/* Your App component goes here */}
</ServerLocation>
</ClientContext.Provider>
)
const initialState = await getInitialState({ App, client })
const content = ReactDOMServer.renderToString(App)
const html = `
<!DOCTYPE html>
<html>
<body>
<div id="app-root">${content}</div>
<script type="text/javascript">
window.__INITIAL_STATE__=${JSON.stringify(initialState).replace(
/</g,
'\\u003c'
)};
</script>
</body>
</html>
`
reply.type('text/html').send(html)
})
API
getInitialState(options)
Returns the serialisable cache after fetching all queries.
options.App
: The react component to renderoptions.client
: An instance of GraphQLClient
from graphql-hooks
options.render
: A custom render function; defaults to ReactDOMServer.renderToStaticMarkup