Search code examples
javascriptvue.jsvuexstorenuxt.js

NuxtJS - Why is my vuex store state is always empty in middleware when access using SSR (Server side rendering)


So i have this middleware files

middleware/authenticated.js

export default function (context) {
    //console.log('context.store.state :>> ', context.store.state);

    if(process.server === true) { //Server Side

        //why is my store state here is always empty when access in SSR
        console.log(context.store.state.authen.UserToken);

    } else { //Client Side

        if(!context.store.state.authen.UserToken) {
            context.redirect('/error');
        } else {
            //Refresh Token
            context.$axios.get("authen/refresh")
                .then((res) => {
                    const payload = {
                        UserToken: res.data.DataReturn.Token,
                        UserId: res.data.DataReturn.UserId,
                        UserEmail: res.data.DataReturn.UserEmail,
                        UserFullname: res.data.DataReturn.UserFullname
                    };
                    context.store.dispatch("authen/SetLogin", payload);
                })
                .catch(function (error) {
                    context.redirect('/error');
                });
        }

    }
}

why it is my state is always empty when accessing in SSR, i can access the store if the call is from client side?


Solution

  • What you are expecting is a response on server. But the work is being done on the client side. To your question nuxtServerInit is the answer. As SSR fires on the server side. So when you fetch your api, you need to fill the store with by calling nuxtServerInit like below.

    actions: {
      nuxtServerInit ({ commit }, { req }) {
        if (req.session.user) {
          commit('user', req.session.user)
        }
      }
    }