Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests.
I am in the process of implementing a route guard to restrict access to specific routes if the session cookie is not present.
"vue": "^3.0.11",
"vue3-cookies": "1.0.1",
The NPM package that has been installed is:
https://www.npmjs.com/package/vue3-cookies
Following this, in main.js
import VueCookies from 'vue3-cookies'
app.use(VueCookies);
And then in router/index.js
function requireAuth(to,from,next){
console.log(this);
console.log(this.$cookies.get('_ga'))
next();
}
const routes = [
{
path: '/',
name: 'ProtectedRoute',
component: ProtectedRoute,
beforeEnter:requireAuth
}
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
Error: [Vue Router warn]: Unexpected error when starting the router: TypeError: Cannot read property '$cookies' of undefined
Attempts have been made with:
this.$cookies.get('_ga')
Vue.$cookies.get('_ga')
window.$cookies.get('_ga')
However, none of them have been successful.
An attempt was also made to import Vue into the index.js file, but it failed due to the inability to import Vue into a component in Vue3 as explained in Vue.js 3: Cannot import Vue global object
The issue appears to be that this, Vue, and window are all undefined. A solution was attempted based on the suggestions here `this` undefined in vue-router beforeEach
router.beforeEach((to,from,next) => {
console.log(router.app); //still undefined!
});
In need of assistance!