1

I'm trying to write SSR-friendly code, keeping in mind a potential migration of my app from SPA to SSR. One of the principles of such code is to avoid statefull singletons which can cause cross request state pollution

The problem comes when I need to use an instance of Vuex, Vue-router, Vue-i18n etc. outside of Vue component. Because the solution in all the respective SO answers is... You guessed it. To create and export a statefull singleton in a separate js file and then import it all over the app:

A simple example

// store.js
export default new Vuex.Store() {} // this is a singleton

// someOtherModule.js
import { store } from './store.js'

Pinia has covered the issue in the docs. They recommend to access the pinia instance via app.$pinia. However they don't specify how do I access the app instance itself.

Also the problem is not limited to these libraries. We write our own modules which work in a similar manner.

Researching the issue I came across this article. It suggests to wipe module cache, so each time you require it all the code is executed again, making it fresh and stateless. Sounds pretty sophisticated, but maybe this is the way? And if not, what is the recommended solution?

Romalex
  • 1,582
  • 11
  • 13
  • The question lacks the context. Where exactly do you need to access these instances and what is your setup? Pinia docs are very specific on that, the example is vue's serverPrefetch hook, and app instance is available as `this` there – Estus Flask Jan 25 '23 at 17:39
  • My setup is vue 2.7. Gradually migrating from options API to composition API and from vuex to pinia. The plan is to switch to Vue 3. Right now it is a pure SPA, but we want to avoid some anti-SSR patterns to be able to migrate to SSR without rewriting the whole codebase one day. Let's say I want to use store in a router navigation guard. Or use router in a store action. Or use i18n in a store. – Romalex Jan 25 '23 at 22:34
  • 1
    All of these places needs to be specifically addressed, there's no single answer to this. Just proceed from the fact that you need to stick to app instance or things that derive from it (composables like useRouter) where possible. E.g. https://github.com/vuejs/pinia/discussions/1092#discussioncomment-2250146 and https://stackoverflow.com/questions/67889690/vue-3-accessing-vue-instance-in-vue-router-outside-a-vue-file . Vue router starts immediately, there may be race condition. Messing with module cache is not an option as it's hacky and won't play well with native ESM, the article is outdated – Estus Flask Jan 25 '23 at 23:10

0 Answers0