Vue-Auth: The property 'beforeEach' is not defined and cannot be read

I'm currently working on integrating my VueJS SPA with a Laravel API.

I came across a plugin called vue-auth that seems to be perfect for handling role-based authentication:

Here's the Github link: https://github.com/websanova/vue-auth

And here's the documentation link:

While the plugin seems to meet my requirements, I'm facing challenges in implementing it in my application.

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'
});

However, when I try to use my application, I encounter this error message in my console:

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

Interestingly, when I switch to using the vue-resource as the http driver (as per the documentation), I face another error:

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

I've been stuck for a few hours now and despite searching extensively on the internet, I haven't found a working solution.

Thank you for taking the time to read this.

Answer №1

For managing role-based authentication in my projects, I often rely on Laravel authentication methods such as JWT or Passport. When using Vue, you can implement role-based authentication by utilizing the beforeEach function within the router. Here is an 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);
        })
    }
})

Answer №2

My modification involved moving the

const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes })
code snippet above the beforeEach function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Is there a way to remove a portion of a string?

Looking to remove a section of a string using JavaScript? I attempted var sentence = "C:\mnt\c\User\Foo\Bar"; var updatedSentence = sentence.replace("mnt\c", ""); But the result was not as expected ...

Customizing v-model in a Vue component

In an effort to simplify certain sections of my HTML code, I have created a small component: <template> <div class="form-group"> <label for="desc">{{label}}</label> <input id="desc" readonly type="text" class="form-con ...

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

I am unable to execute Parcel in my project as it is not generating a distribution folder with the compiled file

I'm in need of some assistance in identifying and resolving an error that I'm having trouble understanding. To start, I initialized the project with the command: npm init -y Next, I installed Parcel using: npm install --save-dev parcel I then ...

Custom validation on the client side using ASP.NET and JavaScript WebMethods

I am encountering an issue with client-side validation using a JavaScript function. On my ASP.NET C# page, I have a WebMethod that successfully validates data entered by the user. The page includes a textbox with an AJAX AutoCompleteExtender, which is work ...

The filtering function using jQuery and ajax

Hello, I'm currently working on a website that compares the prices of domain names. I could use some assistance with a specific function that I'm trying to implement. At the moment, there is a section on the website where users can click on dif ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

What is the method to change lowercase and underscores to capitalize the letters and add spaces in ES6/React?

What is the best way to transform strings with underscores into spaces and convert them to proper case? CODE const string = sample_orders console.log(string.replace(/_/g, ' ')) Desired Result Sample Orders ...

Utilizing optional parameters with React Router

Imagine I have a page at http://www.example.com/page/#/search set up with the following routing: <Router history={hashHistory}> <Route path='/search/' component={SearchPage} /> </Router> When a user performs a search using t ...

Issues with HTTPS in Puppeteer and VUE JS

I am encountering an issue when running tests from NODE net::ERR_CONNECTION_REFUSED at https://localhost:8087 at navigate (node_modules/puppeteer/src/common/FrameManager.ts:190:13) Test Suites: 2 failed, 2 total Tests: 7 failed, 7 total Snapshots: ...

Is it common in Node.js to create multiple instances of "server" objects, but only connect one to a port?

After finishing "Node.js in Action", I'm now piecing together the concepts of Node.js, Connect, and Express. My inquiry revolves around the creation of servers in Node. node_server = http.createServer(); connect_app = Connect(); express_app = Express ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...

Converting an array into an object in Vue.js: A step-by-step guide

Can someone assist me with converting an array to an object in Vue.js? I am trying to extract the name value "Willy" from the array. Here is the array data retrieved from LocalStorage: [{"id":"56b5","name":"Willy","email":"willy@test","password":"1234"}] ...

Unable to delete a dynamically inserted <select> element by using the removeChild method

As someone who is new to coding web applications, I am currently working on a project that involves adding and deleting dropdowns dynamically. Unfortunately, I have run into an issue where the delete function does not work when the button is pressed. Her ...

Dividing the array into distinct subarray groups

I am working with a JavaScript array that contains strings, like this: let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e&quo ...

Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

What is the process of exporting a module assigned to a variable in JavaScript?

My approach to making the require visible in <app></app> is as follows: index.html: <script> var electron = require('electron') </script> <app></app> <script src="bundle.js"></script> App.vue: ...

Troubleshooting: Unable to preview Facebook Page plugin

When I visit the Facebook developer site to get the code for a Facebook page plugin, I use this link. The preview feature works perfectly with pages like "facebook.com/Nike", but when I try it with my own page, "facebook.com/BargainHideout", it doesn&apos ...