I'm currently facing an issue with my router setup and a global beforeEach
hook that validates authentication.
import store from "@/store/store";
const router = new Router({
// routes...
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.getAccessToken) { //undefined store
next("/access/login");
}
}
else {
next();
}
});
export default router;
In my store/store.js
file, I have an action that verifies user credentials and then attempts to redirect to the protected /
route.
import router from "@/router";
//state, getters...
actions: {
login({commit}, authData) {
this._vm.$http.post("/auth/login", authData)
.then(response => {
commit("saveToken", response.data.token);
})
.catch((error) => {
commit("loginError", error.response.data);
});
}
},
mutations: {
saveToken(state, token) {
state.accessToken = token;
router.push({
path: "/"
});
},
loginError(state, data) {
return data.message;
}
}
The challenge I am encountering is that the store
in router.js
seems to be undefined
. Despite thorough checks of imports and naming, the issue persists.
Could this be a result of a circular reference caused by importing router
in the store
and vice versa?
If so, how can I resolve this to access the store from the router or vice versa?
EDIT
Attempts to remove the router import from the store yielded success except for:
router.push({
path: "/"
});
due to the absence of the imported router
.
EDIT: ADDED @tony19 SOLUTION
Following the solution provided by @tony19, things seem to work smoothly. However, upon accessing the /
route, router.app.$store
appears undefined.
The revised code snippet:
router.beforeEach((to, from, next) => {
console.log(`Routing from ${from.path} to ${to.path}`);
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!router.app.$store.getters["authentication/getAccessToken"]) {
next("/access/login");
}
else {
next();
}
}
else {
next();
}
});
An accompanying image showcasing the debugging session: