Vue-Auth : Cannot read property 'beforeEach' of undefined

2.2k Views Asked by At

I'm trying to use my SPA VueJS with a Laravel API.

For handling the role based authentication, I've found the plugin vue-auth :

Github : https://github.com/websanova/vue-auth

Documentation : https://websanova.com/docs/vue-auth/home

This plugin looks great since it looks to fit my needs, but I can't implement it on my app.

import Vue from 'vue';
import auth from '@websanova/vue-auth';
import authBearer from '@websanova/vue-auth/drivers/auth/bearer.js';
import httpAxios from '@websanova/vue-auth/drivers/http/axios.1.x.js';
import routerVueRouter from '@websanova/vue-auth/dist/drivers/router/vue-router.2.x.js';

Vue.use(auth, {
    auth: authBearer,
    http: httpAxios,
    router: routerVueRouter,
    rolesKey: 'role'
});

When I try to use my application, I have this error message in my console :

Uncaught TypeError: Cannot read property 'beforeEach' of undefined
at Auth.beforeEach
at _initInterceptors
at new Auth

And fun fact, when I change my http driver to vue-resource (following the documentation), I have another error :

Uncaught TypeError: Cannot read property 'interceptors' of undefined
at Auth.interceptor
at _initInterceptors
at new Auth

I'm stuck since a few hours now, and I've searched everywhere on internet with no solutions working.

Thanks a lot for reading

2

There are 2 best solutions below

0
On BEST ANSWER

In my way i use laravel auth method like JWT or Passport to handling the role based authentication and vue you can use beforeEach in router for example:

router.beforeEach((to, from, next) => {
    if (to.path == '/login') {
        next();
    } else {
        store.commit('setLoading', true);
        store.dispatch('checkAuth').then(r => {
            store.commit('setUser', r.data);
            next();
        }).catch(e => next('/login?redirect=' + to.path)).finally(() => {
            store.commit('setLoading', false);
        })
    }
})
0
On

I change this by put the const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) before beforeEach