Skip to main content
Exploring Cookie Management in Vue.js

Exploring Cookie Management in Vue.js

in this tutorial, We’ll explore cookie management in the Vue application. We will write cookies, read cookies, and delete cookies in the Vuejs application.

What is the Cookie

An HTTP cookie (web cookie, browser cookie) is a small piece of information that is saved on the client side by the user’s web browser. It helps to communicate client with the web server of the website. They are commonly used to retain user preferences, maintain session information, and store other relevant data.

We can set cookies in a web browser by using an npm package called vue-cookies.

Checkout Other vuejs tutorials:

What’s vue-cookies

This is a simple Vue.js plugin for handling browser cookies. You can use this library to manage cookies in vuejs application. The cookie names cannot be set to [‘expires’,’max-age’, ‘path’, ‘domain’, ‘secure’, ‘SameSite’].

There are the following attributes available in this package:

  • set() : This method helps to set cookies.
  • get(): This method helps to get cookies from cookie objects.
  • remove(): This method helps to remove cookies.
  • Options:
    • expires: set the expiration time of the cookie.
    • domain: The domain for which the cookie is valid.
    • path: It defines the path for which the cookie is valid.
    • secure: This flag allows only HTTPS communication.
    • httpOnly: This flag prevents client-side scripts from accessing the cookie.
    • SameSite: This attribute helps prevent cross-site request forgery (CSRF) attacks.

How To Manage Cookies in Vuejs Application

Let’s integrate cookies into vuejs application using vue-cookies package

Step 1: Installation of vue-cookies</h3 The vue-cookies is lightweight package that facilitates cookie management for vue application. You can isntall it by using npm or yarn:

npm install vue-cookies
or
yarn add vue-cookies

Step 2: Configure vue-cookies

We have installed it and now going to import it into the application and configure vue-cookies:

// main.js or your Vue component file
import Vue from 'vue';
import VueCookies from 'vue-cookies';
Vue.use(VueCookies);

How To Set Cookies

The vue-cookies package has set() method to set cookies using the $cookies object in the vuejs application:

this.$cookies.set('token', 'xs34rfff', '7d');

in the above code, We’re setting a cookie named token with the value ‘xs34rfff’ that expires in 7 days. The third parameter specifies the expiration time, which can be set in seconds, minutes, hours, or days.

How To Get Cookies

You can retrieve the cookie stored value using get() method.

const token = this.$cookies.get('token');
console.log(token);

in the above snippet, we are fetching the value of the token cookie and logging it to the console.

How To Delete Cookies

The remove() method can help to remove cookies from cookie objects.

this.$cookies.remove('token');

The above code will remove the token cookie from the browser.

How To Handle JSON Object

We can also add json object into the cookie.

var user = { id:1, name:'adam',token:'dsdsdsd' };
this.$cookies.set('user',user);

// print user name
console.log(this.$cookies.get('user').name)

Handling Cookie Expiration

We can handle cookie expiration and refresh cookies if they expire by the customized method. Create a method that checks and refreshes cookies when needed:

import VueCookies from 'vue-cookies';

export function refreshToken(token) {
 const token = VueCookies.get(token);
 if (token) {
  const remainingTime = VueCookies.get(cookieName, { expires: '7d', raw: true });
   if (remainingTime < 86400) {
   // Refresh the cookie if less than a day remaining
   VueCookies.set(cookieName, token, '7d');
   }
 }
}

in the above code, we are getting cookie value and check the remaining time of the cookie, and if it’s less than a day, we refresh the cookie.

Conclusion

We’ve explored the cookies manaagement in Vue.js using the vue-cookies library. This library have inbuilt method that helps to read,write and delete cookies, They are also providing some options like, httpOnly, secure flag, sameSite attribute.

Leave a Reply

Your email address will not be published. Required fields are marked *