Vue SPA | vue router check login
Originallypublishedonmyblog[1]WhilemakingLetsOrganise[2]SPA(SinglepageApplication)webumpedintotheissueofproperlycheckingAuthandredirectingwhenauservisitedaroutethatrequiredAuthentication.IfUserisauthenticatedthengototherequestedpageorredirectto/loginpage.Oncetheuserhassuccessfullyloggedinredirectthembacktotherequestedpage.VueRouterhassomethingcalledNavigationGuards[3]totherescue,thatyoucanuseashookbeforeeveryrouteorselectedroutes.NavigationGuardisjustaplainfunctionanditworkslikethefollowing....
Originally published on my blog[1]While making Lets Organise[2] SPA(Single page Application) we bumped into the issue of properly checking Auth and redirecting when a user visited a route that required Authentication. If User is authenticated then go to the requested page or redirect to /login page. Once the user has successfully logged in redirect them back to the requested page.
Vue Router has something called Navigation Guards[3] to the rescue, that you can use as hook before every route or selected routes. Navigation Guard is just a plain function and it works like the following.
function guard(to, from, next){ if(store.state.auth.loggedIn) { // or however you store your logged in state next(); // allow to enter route } else{ next(/login); // go to /login; } } ... // later in the guarded routes export default [{ path: /membership, beforeEnter: guard, // Using guard before entering the route c...