by Sai gowtham

Getting the browser cookie in Vue App

In this tutorial, we are going to learn about how to get a cookie from the browser in Vue using the vue-cookies (npm) package.

Installing the vue-cookies package

The vue-cookies packages help us to easily get the cookies in a vue app.

Run the following command to install the package.

npm install vue-cookies

Now, open your main.js file and add the following (highlighted) configuration.

main.js
import Vue from "vue";
import VueCookies from 'vue-cookies';import App from "./App.vue";

Vue.use(VueCookies);
new Vue({
  render: h => h(App)
}).$mount("#app");

This adds the this.$cookies object to our root app, so that we can access it inside our vue components <script> tag.

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.

Here is an example:

App.vue
<template>
  <div id="app">
     <h1>Vue cookies</h1>
     <button @click="getCookie">Get Cookie</button>  </div>
</template>

<script>
export default {
   methods:{
     getCookie(){
         // it gets the cookie called `username`
      const username = this.$cookies.get("username");      console.log(username);
     }
   }
};
</script>

Note: If you set an httpOnly to the response, then you can’t access it inside the vue app.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course