Skip to content

Instantly share code, notes, and snippets.

@kvnam
Last active July 21, 2019 15:34
Show Gist options
  • Save kvnam/36b45f8db4acc6b862c7d5ae678d2991 to your computer and use it in GitHub Desktop.
Save kvnam/36b45f8db4acc6b862c7d5ae678d2991 to your computer and use it in GitHub Desktop.
Round One SSR
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import express from 'express';
//My HTML wrapper component where I insert the string returned
// by renderToString()
import Html from './html';
// The basic App component used by our React application
import App from '../src/App';
const app = express();
app.use(express.static(path.resolve(__dirname, './build'), { index: false }));
// Setting this to capture all paths for now, since we only have one component to display
app.get('*', (req, res) => {
const application = <App />;
// Convert the App component into a string
const content = ReactDOMServer.renderToString(application);
const html = <Html content={content} />;
// Send back the final string to the browser, which will detect the HTML tags and
// render the file correctly.
res.send(`<!doctype html>\n${ReactDOMServer.renderToStaticMarkup(html)}`);
});
export default app;
import React from 'react';
// This is where the string content returned is inserted into
// our final HTML file
const Html = ({ content }) => (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Round One SSR App</title>
</head>
<body>
<div id="root" dangerouslySetInnerHTML={{ __html: content }} />
</body>
</html>
);
export default Html;
const http = require('http');
const app = require('./server-app');
const server = http.createServer(app.default);
const PORT = process.env.PORT || 8000;
// Super bare bones server is up and ready!
server.listen(PORT, function(){
console.log(`App listening on ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment