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

4

10

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.

Earreach answered 19/8, 2019 at 14:28 Comment(0)
S
14

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')
  }
}
Schubert answered 19/8, 2019 at 14:39 Comment(2)
Can I somehow use vue-cookies?Earreach
js-cookie does everything I needed vue-cookies to do. In my case, there is no need to implement vue-cookies over js-cookieBrier
S
7

you can do (in store.js)

import Vue from 'vue'

...

someAction () {
    Vue.prototype.$cookies.set("token", response.token, "7d");
}
Span answered 19/8, 2019 at 15:11 Comment(2)
How reasonable is it to import Vue?Guilbert
@PavelLevin I have been using this pattern for quite a while, and have not found any drawbacks yet. You can safely import Vue anywhere in your project. Imports are properly encapsulated when bundled.Span
N
7

When using vue-cookies in your app

In your store.js, you can

import cookie from 'vue-cookies'

.....

action(){
   cookie.get('token');
}
Nureyev answered 23/8, 2019 at 12:5 Comment(0)
P
-3

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

Platus answered 16/1, 2021 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.