Skip to content

Instantly share code, notes, and snippets.

@alexnm
Created March 24, 2018 16:30
Show Gist options
  • Save alexnm/cbf568202681c48f941eaa183c7e6a11 to your computer and use it in GitHub Desktop.
Save alexnm/cbf568202681c48f941eaa183c7e6a11 to your computer and use it in GitHub Desktop.
Server file handling redux state
/* ... */
import { Provider as ReduxProvider } from "react-redux";
/* ... */
app.get( "/*", ( req, res ) => {
const context = { };
const store = createStore( );
store.dispatch( initializeSession( ) );
const jsx = (
<ReduxProvider store={ store }>
<StaticRouter context={ context } location={ req.url }>
<Layout />
</StaticRouter>
</ReduxProvider>
);
const reactDom = renderToString( jsx );
const reduxState = store.getState( );
res.writeHead( 200, { "Content-Type": "text/html" } );
res.end( htmlTemplate( reactDom, reduxState ) );
} );
app.listen( 2048 );
function htmlTemplate( reactDom, reduxState ) {
return `
/* ... */
<div id="app">${ reactDom }</div>
<script>
window.REDUX_DATA = ${ JSON.stringify( reduxState ) }
</script>
<script src="./app.bundle.js"></script>
/* ... */
`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment