Skip to content

Instantly share code, notes, and snippets.

@sskoopa
Created November 19, 2016 16:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sskoopa/4893ed60288b1e8d12c70e338387bbd5 to your computer and use it in GitHub Desktop.
Save sskoopa/4893ed60288b1e8d12c70e338387bbd5 to your computer and use it in GitHub Desktop.
Super simple and fast preact server side rendering
function ssr(req, res, url) {
let user = req.user //comes from passport
const preloadedState = { user, url } // Compile an initial state
const store = configureStore(preloadedState) // Create a new Redux store instance
const html = render(<Provider store={store}><Html /></Provider>) // Render the component to a string
const finalState = store.getState() // Grab the initial state from our Redux store
res.send(renderFullPage(html, finalState)) // Send the rendered page back to the client
}
function renderFullPage(html, preloadedState) {
return `<!doctype html>${html}<script>window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')};
var script = window.document.createElement( "script" );
script.src = '/static/js/main.js';
script.async = true;
document.body.appendChild(script);
</script>
`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment