Iworb
Iworb

Reputation: 532

How to use nuxtServerInit in Nuxt as middleware

I splitted my application into server and client one. I'm running server and using nuxt.render middleware in the express and I want to get my user/session/whatever in the nuxt storage. I've made a store/auth.js file:

export const state = () => ({
  user: null
})

export const mutations = {
  SET_USER: (state, user) => {
    state.user = user
  }
}

export const actions = {
  nuxtServerInit ({commit}, {req}) {
    console.log(req)
  },
  async login ({commit}, {username, password}) {
    try {
      const data = this.$axios.$post('/login', {username, password})
      commit('SET_USER', data)
    } catch (err) {
      throw err
    }
  },
  async logout ({commit}) {
    this.$axios.post('/logout')
    commit('SET_USER', null)
  }
}

Nothing happend when page loaded or action performed. There's git repository with complete server and client sides.

UPD For those, who looking for details: Make sure your nuxtServerInit function is in index.js file. You could move it like that:

export const actions = {
  nuxtServerInit ({commit}, {req}) {
    if (req.user) commit('auth/SET_USER', req.user)
  }
}

And auth.js file have no this function anymore. It works in that way.

Upvotes: 1

Views: 2554

Answers (1)

Chanlito
Chanlito

Reputation: 2472

The nuxtServerInit action can only be used inside the store index.js file (or in another word where store is created).

So try to move your nuxtServerInit there.

Upvotes: 1

Related Questions