Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciejsikora/b201a8a791b0c457b6573c25583a5cd8 to your computer and use it in GitHub Desktop.
Save maciejsikora/b201a8a791b0c457b6573c25583a5cd8 to your computer and use it in GitHub Desktop.
Universal Application in React - Server Rendering Part
const renderPage = (req, res, store) => {
const reactPart = renderToString(
<Provider store={store}>
<StaticRouter
location={req.url}
context={{}}>
<App/>
</StaticRouter>
</Provider>
);
res.status(200).send(`
<!DOCTYPE html>
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fat Server Universal App</title>
<link rel="icon" type="image/x-icon" href="/fat.ico" />
</head>
<body>
<div id="app">${reactPart}</div>
<script>
window.__STATE__ = ${JSON.stringify(store.getState()).replace(/</g, '\\u003c')}
</script>
<script type="text/javascript" src="/build.js"></script>
<script type="text/javascript">
initApp("${req.url}");
</script>
</body>
</html>`);
};
// universal routing and rendering
app.get('/', async (req, res) => {
const store = createStore(reducer.main);
store.dispatch(reducer.actions.SET_PAGE(reducer.pages.MAIN));
await reducer.asyncActions.fetchAccounts(store.dispatch);
renderPage(req, res, store);
});
app.get('/account/:id',async (req, res) => {
const store = createStore(reducer.main);
store.dispatch(reducer.actions.SET_PAGE(reducer.pages.SUB));
await reducer.asyncActions.fetchAccountFields(store.dispatch);
await reducer.asyncActions.fetchAccount(req.params.id, store.dispatch);
renderPage(req, res, store);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment