LoginSignup
3
3

More than 3 years have passed since last update.

Nuxt.jsのSSRでミドルウェアを使ってVuexに値をストアする方法

Posted at

SSRのクライアントサイドでレンダリングされる前にstoreに保存するにはミドルウェアを使います。
そのときの参考に残します。
ここでは例にjwtをstoreに保存することをやってみます。普通はcookieとかに保存しますが一例として。

nuxt.config.js
module.exports = {
//省略
router: {
 middleware: 'hoge' //ミドルウェアのファイル名
},
//省略
}
middleware/hoge.js
export default async ({ store }) => {
  if (store.state.auth.token === null) {
    await store.dispatch('auth/setToken')
  }
}
store/fuga.js
import axios from 'axios'

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

export const mutations = {
  login (state, token) {
    state.token = token
  }
}

export const actions = {
  async setToken ({ commit }) {
    await axios.post('http://api.your-site.com/v1/auth', {
      identifier: 'hogefuga@hoga.com',
      password: 'password'
    }).then(res =>
      commit('login', res.data.jwt)
    )
  }
}

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3