Skip to content

Commit

Permalink
server: Add basic server-side renderer
Browse files Browse the repository at this point in the history
  • Loading branch information
smspillaz committed Feb 25, 2018
1 parent bad0a0b commit d3b7ed1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
4 changes: 2 additions & 2 deletions server/middlewares/addProdMiddlewares.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const path = require('path');
const express = require('express');
const ssr = require('../ssr');

module.exports = function addProdMiddlewares(app, options) {
const publicPath = options.publicPath || '/static';
Expand All @@ -12,6 +13,5 @@ module.exports = function addProdMiddlewares(app, options) {
// Except that for now it doesn't work on serverless.
// app.use(compression());
app.use(publicPath, express.static(outputPath));

app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html')));
ssr(app);
};
33 changes: 33 additions & 0 deletions server/ssr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const fs = require('fs');

const React = require('react');
const ReactDOMServer = require('react-dom/server');

// Memory history
const createMemoryHistory = require('history/createMemoryHistory').default;

// Import root containers
const Root = require('../app/app').default;
const messages = require('../app/i18n').translationMessages;
const configureStore = require('../app/configureStore').default;

module.exports = (app) => {
app.use((req, res) => {
const memoryHistory = createMemoryHistory(req.url);
memoryHistory.push(req.originalUrl);
const store = configureStore({}, memoryHistory);
const html = ReactDOMServer.renderToString(
<Root messages={messages} history={memoryHistory} store={store} />
);

// This should read the compiled index.html file when running from the
// webpack bundle and the non-compiled index.html file when running
// from babel-node
fs.readFile('./build/index.html', 'utf8', (err, data) => {
// Set a dummy user agent based on the request user agent.
global.navigator = { userAgent: req.headers['user-agent'] };
res.send(data.replace(/<div id="app">\s*<\/div>/,
`<div id="app">${html}</div>`));
});
});
};

0 comments on commit d3b7ed1

Please sign in to comment.