title: Synchronize Vuex store with server side in Nuxt.js
body: <h2>Problem</h2>
  <p>Below Nuxt middleware</p>
  <pre class="lang-js prettyprint-override"><code>const inspectAuthentication: Middleware = async (): Promise&lt;void&gt; =&gt; {
    await AuthenticationService.getInstance().inspectAuthentication();
  };
  </code></pre>
  <p>is being executed on the server side before return each page's HTML and checks has been user authenticated. If has been, it stores the <code>CurrentAuthenticatedUser</code> in Vuex module:</p>
  <pre class="lang-js prettyprint-override"><code>import {
    VuexModule,
    getModule as getVuexModule,
    Module as VuexModuleConfiguration,
    VuexAction,
    VuexMutation
  } from &quot;nuxt-property-decorator&quot;;
  
  
  @VuexModuleConfiguration({
    name: &quot;AuthenticationService&quot;,
    store,
    namespaced: true,
    stateFactory: true,
    dynamic: true
  })
  export default class AuthenticationService extends VuexModule {
  
    public static getInstance(): AuthenticationService {
      return getVuexModule(AuthenticationService);
    }
  
  
    private _currentAuthenticatedUser: CurrentAuthenticatedUser | null = null;
  
    public get currentAuthenticatedUser(): CurrentAuthenticatedUser | null {
      return this._currentAuthenticatedUser;
    }
  
  
    @VuexAction({ rawError: true })
    public async inspectAuthentication(): Promise&lt;boolean&gt; {
  
      // This condition is always falsy after page reloading
      if (this.isAuthenticationInspectionSuccessfullyComplete) {
        return isNotNull(this._currentAuthenticatedUser);
      }
  
  
      this.onAuthenticationInspectionStarted();
  
      // The is no local storage on server side; use @nuxtjs/universal-storage instead
      const accessToken: string | null = DependenciesInjector.universalStorageService.
          getItem(AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE);
  
      if (isNull(accessToken)) {
        this.completeAuthenticationInspection();
        return false;
      }
  
  
      let currentAuthenticatedUser: CurrentAuthenticatedUser | null;
  
      try {
  
        currentAuthenticatedUser = await DependenciesInjector.gateways.authentication.getCurrentAuthenticatedUser(accessToken);
  
      } catch (error: unknown) {
  
        this.onAuthenticationInspectionFailed();
        // error wrapping / rethrowing
      }
  
  
      if (isNull(currentAuthenticatedUser)) {
        this.completeAuthenticationInspection();
        return false;
      }
  
  
      this.completeAuthenticationInspection(currentAuthenticatedUser);
  
      return true;
    }
  
    @VuexMutation
    private completeAuthenticationInspection(currentAuthenticatedUser?: CurrentAuthenticatedUser): void {
  
      if (isNotUndefined(currentAuthenticatedUser)) {
        this._currentAuthenticatedUser = currentAuthenticatedUser;
        DependenciesInjector.universalStorageService.setItem(
          AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE, currentAuthenticatedUser.accessToken
        );
      }
  
      // ...
    }
  }
  </code></pre>
  <p>Above code works fine on server side, but then, on the client side, if to try to get <code>AuthenticationService.getInstance().currentAuthenticatedUser</code>, it will be <code>null</code>!
  I expected that Nuxt.js synchronizes the Vuex store including <code>AuthenticationService</code> with server side, however, it does not.</p>
  <h2>Target</h2>
  <p><code>AuthenticationService</code> must be synchronized with server side, so if user has been authenticated, in the client side <code>AuthenticationService.getInstance().currentAuthenticatedUser</code> it must be non-null even after page reloading.</p>
  <p>There no need to synchronize whole Vuex store in server side (for example, the module responsible floating notification bar is required in the client side only) but if the selective methodology has not been developed, at least synchronizing of whole Vuex store will be enough for now.</p>
  <p><strong>Please don't recommend me the libraries or Nuxt modules for authentication</strong> like <a href="https://github.com/nuxt-community/auth-module" rel="nofollow noreferrer">Nuxt Auth module</a> because here we are talking about synchronizing of the Vuex store with server, not about best Nuxt modules for authentication. Also, the syncronizing of the vuex store between client and server could be used not just for authentication.</p>
  <h3>Update</h3>
  <h4><code>preserveState</code> solution attempt</h4>
  <p>Unfortunately,</p>
  <pre><code>import { store } from &quot;~/Store&quot;;
  import { VuexModule, Module as VuexModuleConfiguration } from &quot;nuxt-property-decorator&quot;;
  
  
  @VuexModuleConfiguration({
    name: &quot;AuthenticationService&quot;,
    store,
    namespaced: true,
    stateFactory: true,
    dynamic: true,
    preserveState: true /* New */
  })
  export default class AuthenticationService extends VuexModule {}
  </code></pre>
  <p>causes</p>
  <pre><code>Cannot read property '_currentAuthenticatedUser' of undefined
  </code></pre>
  <p>error on the server side.</p>
  <p><a href="https://i.stack.imgur.com/oHcse.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oHcse.png" alt="enter image description here" /></a></p>
  <p>The error refers to</p>
  <pre class="lang-js prettyprint-override"><code>@VuexAction({ rawError: true })
  public async inspectAuthentication(): Promise&lt;boolean&gt; {
    if (this.isAuthenticationInspectionSuccessfullyComplete) {
      // HERE ⇩
      return isNotNull(this._currentAuthenticatedUser);
    }
  }
  </code></pre>
  <p>I checked <code>this</code> value. It's a big object; I'll leave the the noticable part only:</p>
  <pre class="lang-js prettyprint-override"><code>{                                                                                                                      
    store: Store {
      _committing: false,
      // === ✏ All actual action here
      _actions: [Object: null prototype] {
        'AuthenticationService/inspectAuthentication': [Array],
        'AuthenticationService/signIn': [Array],
        'AuthenticationService/applySignUp': [Array],
        // ...      
  
    // === ✏ Some mutations ...
    onAuthenticationInspectionStarted: [Function (anonymous)],
    completeAuthenticationInspection: [Function (anonymous)],
    // ...
    context: {
      dispatch: [Function (anonymous)],
      commit: [Function (anonymous)],
      getters: {
        currentAuthenticatedUser: [Getter],
        isAuthenticationInspectionSuccessfullyComplete: [Getter]
      },
      // === ✏ The state in undefined!
      state: undefined
    }
  }
  </code></pre>
  <p>I suppose I need to tell how I initializing the vuex store.
  The <a href="https://stackoverflow.com/a/60886837/4818123">working Nuxt methodology</a> for dynamic modules is:</p>
  <pre class="lang-js prettyprint-override"><code>// store/index.ts
  import Vue from &quot;vue&quot;;
  import Vuex, { Store } from &quot;vuex&quot;;
  
  
  Vue.use(Vuex);
  
  export const store: Store&lt;unknown&gt; = new Vuex.Store&lt;unknown&gt;({});
  </code></pre>
  <h4><code>nuxtServerInit</code> solution attempt</h4>
  <p>Here is the another problem - how to integrate <code>nuxtServerInit</code> in above store initialization method? I suppose, to answer this question it's required the Vuex and <a href="https://github.com/championswimmer/vuex-module-decorators" rel="nofollow noreferrer">vuex-module-decorators</a>. In below <code>store/index.ts</code>, the <code>nuxtServerInit</code> even will not be called:</p>
  <pre class="lang-js prettyprint-override"><code>import Vue from &quot;vue&quot;;
  import Vuex, { Store } from &quot;vuex&quot;;
  
  
  Vue.use(Vuex);
  
  export const store: Store&lt;unknown&gt; = new Vuex.Store&lt;unknown&gt;({
    actions: {
      nuxtServerInit(blackbox: unknown): void {
        console.log(&quot;----------------&quot;);
        console.log(blackbox);
      }
    }
  });
  </code></pre>
  <p>I extracted this problem to <a href="https://stackoverflow.com/questions/69388835/how-to-make-visible-the-nuxtserverinit-action-for-nuxt-js-action-in-the-case-w">other question</a>.</p>