Skip to content

Add SSR support #79

@lesmo

Description

@lesmo

Feature Request

Support for SSR. Current index.web.js is directly calling browser-only objects, which is not possible while being rendered on the server.

Why it is needed

X-All-The-Y
Because localize all the things everywhere!

Possible implementation

I noticed the calls are to navigatorand window objects. Those statements are called as soon as any code imports react-native-localize, so it would be necessary to "delay" that to a later stage, or call them lazily or even conditionally. I don't know how this module's internals work... yet 😏

Code sample

This is a conditional example that would render properly on SSR:

export let constants: LocalizationConstants = generateConstants(
  (navigator && navigator.languages) || [],
);

window && window.addEventListener("languagechange", () => {
  constants = generateConstants(navigator.languages);
  handlers.forEach(handler => handler());
});

The only complication is how to make constants somehow wait or be populated until the browser is ready without breaking anything. This could work:

/* Server Side would need to be populated some othery way... */
export let constants: LocalizationConstants; // Would be undefined until...
document && document.addEventListener("DOMContentLoaded", function(event) { 
  constants = navigator.languages; // We're in business
});

But I'm not sure if an undefined constants would break something, and there would of course need to be a way to know from the client which locale to use. I'll get back if I come up with something.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions