I'm building a spa right now that uses Vue.js as the front end framework which talks to a pure json backend which uses jsonwebtokens. I am more familiar with the React ecosystem. I'm currently not sure how I would protect client side routes in Vue.js. (Not my decision on the framework. I am a new hire. yay!)
In react I would do something like this. In the index.js file of the project. Before the app mounts check whether or not there is a jsonwebtoken in localstorage. If there is, set redux state to logged in. If not set to logged out.
I would then use higher order components to protect my routes so that whenever a user tries to enter a client side protected route, I would use the componentWillMount life cycle method which checks for logged in state. If logged in render the component. Else redirect to log in page.
It seems that higher order components in vue are not able to achieve the same behaviour. Or I just cant find documentation that shows me how to achieve it. Can someone share with me how they would tackle this problem?
As explained in the documentation you can use meta fields on all the routes you want to check for authentication
The example provided in docs:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // make sure to always call next()!
}
})
Or for in component navigation guards you can follow the 2nd link provided by wostex