jeudi 3 septembre 2020

Dealing with singletons/modules with local state when Server Side Rendering JS

In JS all modules are cached (by Node directly or by Webpack in a browser, for example) so essentially they're all singletons by default.

Some of them sometimes contain a state, like the module in this example:

// foo.js

let state = 0;

export function incrementNumber() {
  state++;
}

export function getNumber() {
  return state;
}

The issue with these is that when they're made for the client-side, the assumption is that the state will only be global for that specific browser tab session - once the page is refreshed/left, the state is gone. However, if you try to Server-side render a JS App that has modules like this, the stateful singleton is going to act differently and the state is going to leak between all users.

Considering that I have a client-side Vue application that has some modules like this and I want to implement SSR - what would be the best way to refactor such modules so that they work correctly? I need the component to be a singleton in the client-side, but I don't want there to be invididual instances of it for each separate request in the server-side.

Aucun commentaire:

Enregistrer un commentaire