Skip to content

Instantly share code, notes, and snippets.

@jacobp100
Last active July 15, 2016 09:59
Show Gist options
  • Select an option

  • Save jacobp100/aab0c96d9762c87c649f183ecae76dc6 to your computer and use it in GitHub Desktop.

Select an option

Save jacobp100/aab0c96d9762c87c649f183ecae76dc6 to your computer and use it in GitHub Desktop.
// SETUP STORE
server.all('*', (req, res, next) => {
req.store = createStore(reducers, middlewares);
next();
});
// FORM HANDLERS
server.post('*', async (req, res, next) => {
try {
const actionParams = req.body;
const actionCreator = actionCreators[actionParams['action-creator']];
const action = actionCreator(actionParams);
await req.store.dispatch(action);
} finally {
next();
}
});
// RENDER PAGE
// All from react-router documentation
server.all('*', (req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(301, redirectLocation.pathname + redirectLocation.search);
} else if (error) {
res.status(500).send(error.message);
} else if (!renderProps) {
res.status(404).send('Not found');
} else {
const reduxState = req.store.getState();
const markup = renderToString(
<Provider store={req.store}>
<RouterContext {...renderProps} />
</Provider>
);
res.send(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cat Demo</title>
</head>
<body>
<div id="root">
${markup}
</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(reduxState)}
</script>
<script src="dist/client.js"></script>
</body>
</html>
`);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment