Skip to content

Commit

Permalink
implements server side rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
rogerjin12 committed Jun 2, 2017
1 parent c374c71 commit 525c625
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
"version": "0.0.1",
"description": "React server rendering example",
"scripts": {
"start": "webpack"
"start": "webpack && babel-node server.js"
},
"author": "Roger Jin",
"dependencies": {
"buttercms": "^1.0.15",
"express": "^4.15.3",
"path": "^0.12.7",
"react": "^0.14.8",
"react-dom": "^0.14.8"
Expand Down
29 changes: 29 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Hello from './Hello.js';

function handleRender(req, res) {
const html = ReactDOMServer.renderToString(<Hello />);

fs.readFile('./index.html', 'utf8', function (err, data) {
if (err) throw err;

const document = data.replace(/<div id="app"><\/div>/, `<div id="app">${html}</div>`);

res.send(document);
});
}

const app = express();

// Serve built files with static files middleware
app.use('/build', express.static(path.join(__dirname, 'build')));

// Serve requests with our handleRender function
app.get('*', handleRender);

// Start server
app.listen(3000);

0 comments on commit 525c625

Please sign in to comment.