Use case: Vue3 app using express as API backend. Express uses express-sessions to establish a server-side session which is sent to the browser and received in every subsequent request.
I'm trying to create a route guard to prevent access to certain routes if the session cookie doesn't exist.
"vue": "^3.0.11",
"vue3-cookies": "1.0.1",
I've installed the following NPM package
https://www.npmjs.com/package/vue3-cookies
Then in main.js
import VueCookies from 'vue3-cookies'
app.use(VueCookies);
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
I've tried
this.$cookies.get('_ga')
Vue.$cookies.get('_ga')
window.$cookies.get('_ga')
None work.
I've also tried importing Vue into the index.js file but it fails, probably because in Vue3 you cannot import Vue into a component Vue.js 3: Cannot import Vue global object
The problem seems to be that this,Vue and window are all undefined. I've also tried the solution here `this` undefined in vue-router beforeEach
router.beforeEach((to,from,next) => {
console.log(router.app); //still undefined!
});
Help!
document.cookie? and see if it outputs something?