Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie in vuejs?

What is the best practice for setting a cookie in vuejs? I use SSR, so I guess I can’t use localStorage.

What is the best approach here?

like image 643
Ic3m4n Avatar asked Jun 08 '18 06:06

Ic3m4n


People also ask

How do you set data in cookies in vue JS?

Setting the cookie$cookies. set() method by passing a cookie-name, cookie-value as arguments. Here is an example, that sets a cookie to the webpage by clicking the Set Cookie button. You can also set the cookie expiration time like this.

How do I get cookies in Vuejs?

To get a cookie inside the vue component, we need to use the this. $cookies. get() method by passing a cookie-name as its argument. Note: If you set an httpOnly to the response, then you can't access it inside the vue app.

What is VUEX in vue JS?

Vuex is a state management pattern + library for Vue. js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.


3 Answers

You could use the vue-cookie or vue-cookies npm package. You can set a cookie in the created method.

created() {
   this.$cookie.set("keyName", keyValue, "expiring time")
}
like image 156
Devansh Saini Avatar answered Oct 11 '22 20:10

Devansh Saini


You can also do it in a plain JavaScript without using extensions.

Lets say you want to store a token with expiry of 24 hours inside axios POST response.

axios
  .post("url", dataToSend)
  .then(function (response) {
    if (response.status == 200) {
      let d = new Date();
      d.setTime(d.getTime() + 1 * 24 * 60 * 60 * 1000);
      let expires = "expires=" + d.toUTCString();
      document.cookie =
        "Token=" + response.data.Token + ";" + expires + ";path=/";
    }
  })
  .catch(function (error) {
    console.log(error);
  });
like image 39
khan Avatar answered Oct 11 '22 19:10

khan


Use vue-cookies

To use:

<script src="https://unpkg.com/[email protected]/vue-cookies.js"></script>
<script>
  $cookies.set('cookie_name', 'cookie_value');
</script>
like image 6
mpalencia Avatar answered Oct 11 '22 19:10

mpalencia