Skip to content

Instantly share code, notes, and snippets.

@drenther drenther/server.index.js
Last active Jul 9, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.