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!
Vue Router 4 removes router.app
, but you could add it yourself when setting up the router:
// main.js
import router from './router'
const app = createApp(App)
app.use(router)
router.app = app
app.mount('#app')
Then in the router config script, you could use that reference to get at app.config.globalProperties.$cookies
(the global added by vue3-cookies
):
// router.js
const router = createRouter({
history: createWebHistory(),
routes
})
function requireAuth(to, from, next) {
const { $cookies } = router.app.config.globalProperties
console.log('_ga', $cookies.get('_ga'))
next()
}
export default router