https://github.com/jackdclark/graphql-hooks-ssr
Server-side rendering utils for graphql-hooks
https://github.com/jackdclark/graphql-hooks-ssr
Last synced: about 1 year ago
JSON representation
Server-side rendering utils for graphql-hooks
- Host: GitHub
- URL: https://github.com/jackdclark/graphql-hooks-ssr
- Owner: jackdclark
- License: other
- Created: 2019-03-05T14:57:55.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-03-05T14:56:11.000Z (over 7 years ago)
- Last Synced: 2025-03-17T10:08:50.860Z (over 1 year ago)
- Language: JavaScript
- Size: 31.3 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## 📣 NOTICE 📣
This repository has moved into the [`graphql-hooks` monorepo](https://github.com/nearform/graphql-hooks) and is no longer maintained here.
🏡 New home: [graphql-hooks-ssr](https://github.com/nearform/graphql-hooks/tree/master/packages/graphql-hooks-ssr).
Please raise any issues for this package in the above repository, thank you.
---
# 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`.
```js
const { GraphQLClient } = require('graphql-hooks')
const memCache = require('graphql-hooks-memcache');
const { getInitialState } = require('graphql-hooks-ssr');
const { ServerLocation } = require('@reach/router');
// NOTE: use can use any 'fetch' polyfill
const fetch = require('isomorphic-unfetch');
app.get('/', async (req, reply) => {
// Step 1: Create the client inside the request handler
const client = new GraphQLClient({
url: 'https://domain.com/graphql',
cache: memCache(),
fetch
});
// Step 2: Provide the `client`
// Optional: If your app contains a router, you'll need to tell it which route the user is on
// based on the request.. this example uses @reach/router
const App = (
{/* Your App component goes here */}
);
// Step 3: Use the getInitialState method from graphql-hooks-ssr
// Pass in App + GraphQL client
const initialState = await getInitialState({ App, client });
// Step 4: Render the your App - all queries will now be cached
const content = ReactDOMServer.renderToString(App);
// Step 5: Serialise the initialState object + include it in the html payload
const html = `
${content}
window.__INITIAL_STATE__=${JSON.stringify(initialState).replace(
/</g,
'\\u003c'
)};
`;
reply.type('text/html').send(html);
});
```
### API
#### `getInitialState(options)`
Returns the serialisable cache after fetching all queries.
- `options.App`: The react component to render
- `options.client`: An instance of `GraphQLClient` from `graphql-hooks`
- `options.render`: A custom render function; defaults to `ReactDOMServer.renderToStaticMarkup`