Last active
July 9, 2019 18:21
-
-
Save drenther/2023dc0e4daa1e8dadf5352c0ac632aa to your computer and use it in GitHub Desktop.
server/index.js for react-ssr
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
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}`); | |
}); |
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
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