Skip to content

Instantly share code, notes, and snippets.

@narendrashetty
Created January 8, 2017 16:49
Show Gist options
  • Save narendrashetty/53f70016885c6005a6844fb612ec2aef to your computer and use it in GitHub Desktop.
Save narendrashetty/53f70016885c6005a6844fb612ec2aef to your computer and use it in GitHub Desktop.
server.use((req, res)=> {
match({
'routes': routes,
'location': req.url
}, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
// Create a new Redux store instance
const store = configureStore();
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
);
const preloadedState = store.getState();
fs.readFile('./dist/index.html', 'utf8', function (err, file) {
if (err) {
return console.log(err);
}
let document = file.replace(/<div id="app"><\/div>/, `<div id="app">${html}</div>`);
document = document.replace(/'preloadedState'/, `'${JSON.stringify(preloadedState)}'`);
res.setHeader('Cache-Control', 'public, max-age=31536000');
res.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString());
res.send(document);
});
} else {
res.status(404).send('Not found')
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment