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