How to restrict page access to unlogged users with VueJS?
You can use https://router.vuejs.org/guide/advanced/navigation-guards.html beforeEach
to check if the current user is logged or not and do what you need to do :).
your routes:
...
{
path:'/profile',
meta:{guest:false},
component:ProfileComponent
},
...
example :
router.beforeEach((to, from, next) => {
if (!to.meta.guest) {
// check if use already logged
// if true then go to home
return next({path:'/'}); // '/' is home page for example
// else then continue to next()
}
return next();
});
You can use also beforeEnter
param if you have only few routes which should be protected.
routes.js
import {ifAuthenticated} from "../middleware/authentication";
{
path: '/test',
name: 'Test',
component: Test,
beforeEnter: ifAuthenticated
},
authentication.js
import store from '../../store'
export const ifAuthenticated = (to, from, next) => {
store.dispatch('User/getUser')
.then(() => {
next()
})
.catch(() => {
next({ name: 'Login', query: { redirect_to: to.fullPath } })
})
}
Example with usage of vuex.