How do I get Vue-Cookies to work in Vue-Router Component

20,445

Solution 1

The solution was to change all of the 'this.$cookies' objects to 'window.$cookies' like this:

router.beforeEach((to, from, next) => {
  // Look at all routes
  router.options.routes.forEach((route) => {
    // If this is the current route and it's secure
    if (((to.matched[0].path === route.path || to.matched[0].path === '') && route.path === '/') && route.secure) {
      // Check if there's a cookie and verify it
      // Check if user has cookie "SAMLSession"
      if (window.$cookies.isKey('SAMLSession')) {
        // Sets the value of "SAMLSession" cookie to a variable
        const sessionId = window.$cookies.get('SAMLSession');
        // Runs function checkSaml located above, then once that completes....
        checkSaml(sessionId).then(result => {
          // Check if the session id is valid via Express, noted by a response of "OK" if good, and "BAD!" if not valid
          if (result.data === 'OK') {
            // If it's good, allow the user to see the page
            next();
          } else {
            // If it's not valid, set a cookie of the page the user was trying to access and then sign them in
            window.$cookies.set('referLocation', to.path, Infinity, '/');
            next('/saml/login');
          }
        });
      } else {
        // If it's not a cookie, set a cookie of the page the user was trying to access and then sign them in
        window.$cookies.set('referLocation', to.path, Infinity, '/');
        next('/saml/login');
      }
    }
  });
  // If nothing has happened, allow the user to visit the page
  next();
});

Solution 2

I was facing the same problem, trying to figure why this is undefined in router which makes this.$cookies error.

Here is how I did it.

//add this in the router index.js
import Vue from 'vue'

And then, I can access cookie variable from Vue

beforeEnter: (to, from, next) => {
    let access_token = Vue.cookie.get('access_token')
    if (access_token == null) {
        // user doesn't have access token, redirect to login
        next({ name: 'login' })
    }
    else {
        // user has access token, user can open the page
        next()
    }
},
Share:
20,445
Marvin WordWeaver Parsons
Author by

Marvin WordWeaver Parsons

I am an Application Developer specializing in Web Applications. I work with many different web technologies including the basic HTML, CSS and JS, but also more advanced technologies such as VueJS, NPM, Drupal, PHP, MySQL and Linux Administration. It is also my responsibility to create, maintain and adhere to Disaster Recovery plans for the Applications managed and to introduce new technology to deliver to our users. In addition to Web Applications, I also work on a Business Intelligence application that utilized Talend Open Studio Big Data to ETL data from several different internal and external sources to provide internal company BI and ML reports and data.

Updated on March 11, 2020

Comments

  • Marvin WordWeaver Parsons
    Marvin WordWeaver Parsons about 4 years

    I have a router index.js file that loads Vue, Vue-Router and Vue-Cookies like so:

    import Vue from 'vue';
    import Router from 'vue-router';
    import VueCookies from 'vue-cookies';
    
    Vue.use(Router);
    Vue.use(VueCookies);
    

    I then define all of my routes like this:

    const router = new Router({
      routes: [
        {
          path: '*',
          name: 'erorr',
          secure: false,
          component: error404,
        },
        {
          path: '/',
          name: 'Home',
          secure: false,
          component: home,
        },
        {
          path: '/clp',
          name: 'CLP',
          secure: true,
          component: clpHome,
        },
        {
          path: '/saml/login',
          name: 'samlLogin',
          secure: false,
          component: samlLogin,
        },
        {
          path: '/saml/logout',
          name: 'samlLogout',
          secure: false,
          component: samlLogout,
        },
        {
          path: '/user/profile',
          name: 'userProfile',
          secure: false,
          component: userProfile,
        },
      ],
    });
    

    After this, it is checking to see if a cookie is set:

    router.beforeEach((to, from, next) => {
      // Look at all routes
      router.options.routes.forEach((route) => {
        // If this is the current route and it's secure
        if (((to.matched[0].path === route.path || to.matched[0].path === '')/* && route.path === '/'*/) && route.secure) {
          // Check if there's a cookie and verify it
          // Check if user has cookie "SAMLSession"
    

    This is where the error pops up, "TypeError: Cannot read property 'isKey' of undefined" When I attempt to console.log(this.$cookies); it is returned 'undefined' as well.

          if (this.$cookies.isKey('SAMLSession')) {
            // Sets the value of "SAMLSession" cookie to a variable
            const sessionId = this.$cookies.get('SAMLSession');
            // Runs function checkSaml located above, then once that completes....
            checkSaml(sessionId).then(result => {
              // Check if the session id is valid via Express, noted by a response of "OK" if good, and "BAD!" if not valid
              if (result.data === 'OK') {
                // If it's good, allow the user to see the page
                next();
              } else {
                // If it's not valid, set a cookie of the page the user was trying to access and then sign them in
                this.$cookies.set('referLocation', to.path, Infinity, '/');
                next('/saml/login');
              }
            });
          } else {
            // If it's not a cookie, set a cookie of the page the user was trying to access and then sign them in
            this.$cookies.set('referLocation', to.path, Infinity, '/');
            next('/saml/login');
          }
        }
      });
      // If nothing has happened, allow the user to visit the page
      next();
    });
    

    This configuration was working a few days ago, and now it is not loading VueCookies, Any advice in troubleshooting it would be appreciated.

  • colm.anseo
    colm.anseo about 5 years
    using window rather than Vue mechanisms seems like a hack.
  • Marvin WordWeaver Parsons
    Marvin WordWeaver Parsons about 5 years
    The cookie is set by Express and passed on to Vue through window in the next('/saml/login') endpoint. When the cookie is produced, for authentication, it is done on the back-end, then passed forward and validated on each request.
  • DazBaldwin
    DazBaldwin over 4 years
    Good to know that the variable changes to cookie instead of $cookie. I was trying to get Vue.$cookie but getting null. Thanks.
  • Shujat Munawar
    Shujat Munawar about 4 years
    I am getting 'TypeError: Cannot read property 'get' of undefined' Any idea?
  • Christhofer Natalius
    Christhofer Natalius about 4 years
    @SHUJATMUNAWAR there are 2 big plugin for this. vue-cookie and vue-cookies Try to use it depends on what plugin you are using, Vue.cookie or Vue.$cookies
  • nicoramirezdev
    nicoramirezdev over 3 years
    yeah, still seems hackish