Vue Router Protection
This article will explain, how can we protect the router in vue with the explanations and code. If you expect from this artical what is vue router? and how can we use it?, This is not for you. You can check those in the vue router official page.
In the real word scenario, when you work with any web framework you have to do router protection. For an example, if the user not logged in to the system users can’t see specific pages, how can we do this protection. Here it is, This article will explain you with each steps.
This project has two pages, One is login page and other one is home page. The problem with the existing application is, without user logged in to the application, if the user go to the home page application allows the user to see the home page content.
Step 1 : Add the route for Login, Home and Other pages
Step 2 : Identify where to protect the router
In order to protect the vue router, we are going to use the vue navigation guards. By using vue navigation guards, we can validte before or after entering to the route. In order to check user is logged in or not we will use before enter to router.
BeforeEach guard will take 3 parameters,
to is the target router object being navigated to.
from is the current route being navigated away from.
next is this function must be called to resolve the hook. The action depends on the arguments provided.
Okay……. wait, how can I protect the vue router using beforeEach?
Step 3 : Add meta property to each route
Vue router supports something called meta fields, which we can include when we defining the route. Keep it in mind that the meta property expects and object.
Let’s add the meta tag.
In the beforeEach guard, we are going to use isAuth to check whether that route should be protected or not.
Step 4 : Add the validation code for required route
In our route guard, we can now access the meta fields.
Step 5 : Fix the issue in the code
Wait…
Each route object in the route configuration is called a route record. Route records may be nested, so if a route is matched It can potentially match more than one route record. Therefor, the best way to check if any of the matched routes has the specified meta, by using the route.mathced property. By using the javascript build in function, we can check isAuth is true or false.
Finally, we came to the point where we can protect the router and how we can protect the router. We can easily do the logic with the few lines of code.
The full project code is in the GitHub.