atinux / vue-adonis

Boilerplate for using AdonisJS + Vue.js with server-side rendering

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

An example using JWT

dan-gamble opened this issue · comments

Hey, i'm loving this template.

I've been trying to integrate JWT auth and i'm struggling to persist the logged in state. I was storing it in Vuex but that isn't persistant. I was gonna store it in localStorage but that doesn't exist on node for the server side. I'm sure it's something simple i'm missing but i'm quite new to all of this :)

Hi @dan-gamble

Just to be sure, are you using JWT with Adonis JS on the same server? Or is it from another distant server?

With AdonisJS on the same server :)

Here and example, tell me if you need some explanations, but I find it pretty explicit:

File App.vue:

<script>
export default {
  beforeMount () {
    // Before mount is called only on the client-side
    if (typeof localStorage !== 'undefined' && localStorage.getItem('JWT')) {
      this.$store.commit('SET_JWT', localStorage.getItem('JWT'))
    }
  },
  methods: {
    // It can be in sub-component, in your login form for example
    login () {
      // Get back the token from the API
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('JWT', token) // Set token in localStorage (client-side)
      }
      this.$store.commit('SET_JWT', token)
    }
  }
}
</script>

And in your store/index.js:

const store = new Vuex.Store({
  state: {
    JWT: null
  },
  mutations: {
    SET_JWT (state, token) {
      state.JWT = token
    }
  }
})

I'll give that a shot and see how it goes, thanks!

Legend, this helped me a ton. Main thing i was struggling with was the beforeMount, wasn't aware it wasn't called server side. Thanks!