Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
export function serializeServerDataToJsonString(data: Object): string {
const jsonString = JSON.stringify(data);
return jsonString
.replace(/<\/script/gim, '</_escaped_script')
.replace(/<!--/gm, '\\u003C!--')
.replace(new RegExp('\u2028', 'g'), '\\u2028')
.replace(new RegExp('\u2029', 'g'), '\\u2029')
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\f/g, '\\f')
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/&/g, '\\&');
}
export function deserializeServerDataFromJsonString(jsonString: string): Object {
try {
return JSON.parse(jsonString.replace(/<\/_escaped_script/gm, '</script'));
} catch (error) {
console.error(error, { errorName: 'Failed to deserialize server data' });
return JSON.parse(jsonString);
}
}
@eliseumds

This comment has been minimized.

Copy link
Owner Author

@eliseumds eliseumds commented Dec 31, 2019

That's how I render my application state:

const escapedReduxStateJsonString = serializeServerDataToJsonString(store.getState());

return (
  <script
    dangerouslySetInnerHTML={{
      __html: `window.MY_SERVER_DATA='${escapedReduxStateJsonString}';`,
    }}
    charSet="UTF-8"
  />
);

And then the rehydration on the client:

const store = createStore(
  deserializeServerDataFromJsonObject(window.MY_SERVER_DATA)
);
@eliseumds

This comment has been minimized.

Copy link
Owner Author

@eliseumds eliseumds commented Jan 6, 2020

Some improvements were suggested by minitech on HackerNews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment