Skip to content

Instantly share code, notes, and snippets.

@selbekk
Created July 27, 2017 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selbekk/572a3ec92d9616dea93700eaf0460282 to your computer and use it in GitHub Desktop.
Save selbekk/572a3ec92d9616dea93700eaf0460282 to your computer and use it in GitHub Desktop.
Universal server rendering
const path = require('path');
const fs = require('fs');
const React = require('react');
const { renderToString } = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const { ServerStyleSheet } = require('styled-components');
const { default: App } = require('../src/containers/App');
const indexFile = fs.readFileSync(path.resolve(__dirname, '..', 'build', 'index.html'), 'utf8');
global.window = undefined;
global.document = undefined;
module.exports = function universalLoader(req, res) {
const css = new ServerStyleSheet();
const context = {};
// Create the markup from the React application
const markup = renderToString(
css.collectStyles(
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
)
);
if (context.url) {
return res.redirect(context.url);
}
console.log(indexFile);
const html = indexFile
.replace('{{SSR}}', markup)
.replace('{{CSS}}', css.getStyleTags());
res.send(html);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment