unistore icon indicating copy to clipboard operation
unistore copied to clipboard

SSR support

Open sammdec opened this issue 7 years ago • 3 comments

This might be out of the scope of the project but is it possible to do server side rendering/ rehydration with unistore?

sammdec avatar Feb 27 '18 22:02 sammdec

Not out-of-scope at all! I don't know that it'd end up being in the Unistore repo, but certainly I'd love to show an example of how to do it.

Here's roughly how it looks:

function serverRender() {
  const store = createStore();
  let html = renderToString(<App store={store} />);
  const data = store.getState();
  html = html.replace(/(<body(\s.?)?>)/, '$1<script>window.DATA='+JSON.stringify(data)+'</script>');
  return html;
}

function clientRender() {
  const store = createStore(window.DATA);
  render(<App store={store} />, document.body);
}

developit avatar Apr 27 '18 03:04 developit

use devalue instead of JSON.stringify to prevent XSS

'$1<script>window.DATA='+devalue(data)+'</script>'

stereobooster avatar May 22 '18 22:05 stereobooster

That is a fantastic suggestion @stereobooster.

developit avatar May 25 '18 14:05 developit