Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active July 9, 2019 18:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/2023dc0e4daa1e8dadf5352c0ac632aa to your computer and use it in GitHub Desktop.
Save drenther/2023dc0e4daa1e8dadf5352c0ac632aa to your computer and use it in GitHub Desktop.
server/index.js for react-ssr
import express from 'express';
import cors from 'cors';
import React from 'react';
import { Helmet } from 'react-helmet';
import { renderToString } from 'react-dom/server';
import { matchPath, StaticRouter } from 'react-router-dom';
import App from '../shared/App';
import routes from '../shared/routes';
import template from './template';
const app = express();
app.use(cors());
app.use(express.static('public'));
app.get('*', (req, res, next) => {
const activeRoute = routes.find(path => matchPath(req.path, path)) || {};
const apiResponse = activeRoute.getInitialData ? activeRoute.getInitialData(req.path) : Promise.resolve();
apiResponse
.then(data => {
const markup = renderToString(
<StaticRouter location={req.url} context={{ data }}>
<App />
</StaticRouter>
);
const title = Helmet.renderStatic();
res.send(template(data, markup, title));
})
.catch(next);
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
export default (data, markup, title) => `
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
<link rel="stylesheet" href="https://unpkg.com/spectre.css/dist/spectre.min.css">
<script>window.__SERIALIZED_DATA__ = ${JSON.stringify(data)}</script>
</head>
<body>
<div id="app">${markup}</div>
<script src="/bundle.js"></script>
</body>
</html>
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment