Skip to content

Instantly share code, notes, and snippets.

@ryanwild
Created July 9, 2021 06:56
Show Gist options
  • Save ryanwild/dc2e19e8f42f253bed30ae63d28dd160 to your computer and use it in GitHub Desktop.
Save ryanwild/dc2e19e8f42f253bed30ae63d28dd160 to your computer and use it in GitHub Desktop.
React Streaming SSR
const render = async (response: ServerResponse, requestProps: RequestProps) => {
const { page, parameters } = findPage(requestProps.url);
const serverProps = {
request: {
parameters,
...requestProps
}
}
const pageProps = await getPageProps(page, serverProps, {});
const props = Object.assign({}, {
...serverProps,
...pageProps,
});
const serverApp = extractor.collectChunks(
createElement(Server, props)
);
const headComponent = createElement(Head, props);
const head: string = [
(s: string) => () => injectDataProps(props, s),
(s: string) => () => injectIntoHead(extractor.getLinkTags(), s),
(s: string) => () => injectIntoHead(extractor.getStyleTags(), s),
].reduce(
(h: string, fn: Function) => fn(h)(),
renderToStaticMarkup(headComponent)
);
response.write(
firstWrite(head)
);
response.flushHeaders();
renderToNodeStream(serverApp)
.on("end", () => {
response.end(
lastWrite(extractor.getScriptTags())
);
})
.pipe(response, { end: false });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment