How can I access vue-cookies in a vuex store?

14.5k Views Asked by At

In an action, I'm doing:

this.$cookies.set("token", response.token, "7d");
this.$cookies.set("UserId", response.UserId, "7d");

But alas $cookies is not defined.

4

There are 4 best solutions below

2
Diego Armando Maradona On BEST ANSWER

You can install js-cookie library and than access cookie like this in vuex store:

import Cookies from 'js-cookie'

const getters = {
  isLoggedIn: function (state) {
    return !!state.email && !!Cookies.get('access_token')
  }
}
2
Nafees Anwar On

you can do (in store.js)

import Vue from 'vue'

...

someAction () {
    Vue.prototype.$cookies.set("token", response.token, "7d");
}
0
notrexbias On

When using vue-cookies in your app

In your store.js, you can

import cookie from 'vue-cookies'

.....

action(){
   cookie.get('token');
}
0
Dany Henriquez On

Never ever allow a JWT cookie to be accessible by JS. This opens you up for a lot of security vulnerabilities. The accepted answer should never be implemented.

Use a http only and secure cookie only for a production application. Please redesign this part if you are building for production