Set and get cookies in a browser in Vue App

In this post, we will learn how to set cookies in a browser for the Vue webpage.

An HTTP cookie (web cookie, browser cookie) is a small piece of information that is saved on your computer by the user’s web browser while communicating with the web server of the website.

In Vue, we can set cookies in a web browser by using an npm package called vue-cookies.

The vue-cookies allows us to easily set and get our cookies on our Vue website.

So, let’s see how to add the package and implement it on our Vue website.

Install vue-cookies packages

To install the npm package in our Vue project, run this command

npm install vue-cookies --save

Once installed, we need to set it up in the main.js file.

import Vue from 'vue'
import VueCookies from 'vue-cookies'

Vue.use(VueCookies);

This will allow us to use access the cookies instance anywhere on our website using this.$cookies object.

Now, to set a cookie on our vue website, we will use the this.$cookies.set() method. We can pass the cookie name and its value as an argument to this method.

this.$cookies.set("cookieName","cookieValue");

Here, is an example, of setting a cookie to a webpage in vue when the page loads for the first time.

<script>
export default {
   mounted(){
    this.$cookies.set("framework","vuejs")
   }
};
</script>

In the above code, when the page mounts we set (or store) a cookie named “framework” with the value “vuejs“.

To access the cookie that is stored in your browser, we can use this.$cookies.get() method. To get the value of the cookie we have to pass the cookie name as its argument.

this.$cookies.get("framework") // vuejs

This will return the value as “vuejs” when we console log the method.

We can also set an expiration date for our cookie using this vue-cookies package.

To set an expiration date/time for a browser cookie, we have to pass the date/time as the third argument in the this.$cookies.set() method like this.

this.$cookies.set("cookieName","cookieValue","30d");

Here, the cookie will expire after 30 days.

You can also set an expiration time for your website cookies globally in the main.js file using:

Vue.use(VueCookies, { expire: '7d'})

Here, all the cookies in your Vue application will expire after 7 days.

Note: $cookies key names CANNOT be set to [‘expires’, ‘max-age’, ‘path’, ‘domain’, ‘secure’, ‘SameSite’]

Learn more about the package API in vue-cookies.

Scroll to Top