| 1 | import React from 'react'; |
| 2 | import {renderToPipeableStream} from 'react-dom/server'; |
| 3 | |
| 4 | import App from '../src/components/App.js'; |
| 5 | import {resetFeedReveal} from '../src/components/NestedParentExit.js'; |
| 6 | import {resetPageReveal} from '../src/components/Page.js'; |
| 7 | import {resetNestedReveal} from '../src/components/NestedReveal.js'; |
| 8 | |
| 9 | let assets; |
| 10 | if (process.env.NODE_ENV === 'development') { |
| 11 | // Use the bundle from create-react-app's server in development mode. |
| 12 | assets = { |
| 13 | 'main.js': '/static/js/bundle.js', |
| 14 | // 'main.css': '', |
| 15 | }; |
| 16 | } else { |
| 17 | assets = require('../build/asset-manifest.json').files; |
| 18 | } |
| 19 | |
| 20 | export default function render(url, res) { |
| 21 | // Force resuspend on every load |
| 22 | resetFeedReveal(); |
| 23 | resetPageReveal(); |
| 24 | resetNestedReveal(); |
| 25 | res.socket.on('error', error => { |
| 26 | // Log fatal errors |
| 27 | console.error('Fatal', error); |
| 28 | }); |
| 29 | let didError = false; |
| 30 | const {pipe, abort} = renderToPipeableStream( |
| 31 | <App assets={assets} initialURL={url} />, |
| 32 | { |
| 33 | bootstrapScripts: [assets['main.js']], |
| 34 | onShellReady() { |
| 35 | // If something errored before we started streaming, we set the error code appropriately. |
| 36 | res.statusCode = didError ? 500 : 200; |
| 37 | res.setHeader('Content-type', 'text/html'); |
| 38 | pipe(res); |
| 39 | }, |
| 40 | onShellError(x) { |
| 41 | // Something errored before we could complete the shell so we emit an alternative shell. |
| 42 | res.statusCode = 500; |
| 43 | res.send('<!doctype><p>Error</p>'); |
| 44 | }, |
| 45 | onError(x) { |
| 46 | didError = true; |
| 47 | console.error(x); |
| 48 | }, |
| 49 | } |
| 50 | ); |
| 51 | // Abandon and switch to client rendering after 5 seconds. |
| 52 | // Try lowering this to see the client recover. |
| 53 | setTimeout(abort, 5000); |
| 54 | } |