Created
July 27, 2017 10:57
-
-
Save selbekk/572a3ec92d9616dea93700eaf0460282 to your computer and use it in GitHub Desktop.
Universal server rendering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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