Skip to content

Instantly share code, notes, and snippets.

@whilelucky
Last active October 27, 2017 03:04
Show Gist options
  • Save whilelucky/33142b2eae0806210ecead567dceab75 to your computer and use it in GitHub Desktop.
Save whilelucky/33142b2eae0806210ecead567dceab75 to your computer and use it in GitHub Desktop.
streaming
earlyChunk(route) {
return `
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="${assets.main.css}">
<link rel="preload" as="script" href="${assets.webpackManifest.js}">
<link rel="preload" as="script" href="${assets.vendor.js}">
<link rel="preload" as="script" href="${assets.main.js}">
${!assets[route.name] ? '' : `<link rel="preload" as="script" href="${assets[route.name].js}">`}
</head>`;
},
lateChunk(app, head, initialState) {
return `
<body>
<div id="root">${app}</div>
<script>window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}</script>
<script src="${assets.webpackManifest.js}"></script>
<script src="${assets.vendor.js}"></script>
<script src="${assets.main.js}"></script>
</body>
</html>
`;
},
const serverRenderedChunks = async (req, res, renderProps) => {
const route = renderProps.routes[renderProps.routes.length - 1];
const store = configureStore();
//set the content type since you're streaming the response
res.set('Content-Type', 'text/html');
//flush the head with css & js resource tags first so the download starts immediately
const earlyChunk = html.earlyChunk(route);
res.write(earlyChunk);
res.flush();
//call & wait for api's response, set them into state
await loadOnServer({ ...renderProps, store });
//flush the rest of the body once app the server side rendered
const lateChunk = html.lateChunk(
renderToString(
<Provider store={store} key="provider">
<ReduxAsyncConnect {...renderProps} />
</Provider>,
),
Helmet.renderStatic(),
store.getState(),
route,
);
res.write(lateChunk);
res.flush();
//let client know the response has ended
res.end();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment