How to implement Navigation Guards Vue

In How to use Firebase Authentication with Vue we started to develop an application with a Simple Email and Password Authentication system. Our Application basically consisted of the functionality to:

  • Register
  • Login
  • Logout

We are now going to build on this functionality and use the Navigation Guards provided by the Vue-Router and the Firebase Authentication to protect pages within our application.

Navigation Guards provided by vue-router are primarily used to guard navigation within an application by either by redirecting it or cancelling it.

There are a number of ways to hook into the route navigation process: globally, per-route, or in-component.

In the example, we will take a look at how to implement Global Navigation Guard, to ensure that users login to the application to access whichever functionality we want to secure.

What are Vue Router Navigation guards

Vue Router is used to switch components depending on the route requested.

Vue-router does not implement or provide any AJAX call functionality for role-based authentication protection for example.

This functionality is to be implemented making use of guards, that provide hooks, where we plug into.

Vue Router has 3 types of guards:

  • Global guards
    – These are called each time the URL changes
    – Guards: beforeEachbeforeResolveafterEach
  • Route guards
    – These are only called when the associated ROUTE is matched
    – Guards: beforeEnter
  • Route Component guards
    – These are only called when a ROUTE COMPONENT is used/unused
    – Guards: beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave

Advice

All guards except afterEach are asynchronous methods called in sequence, therefore, require explicit next() method to notify the router when complete and continue the sequence.

Global Navigation Guards

Global before guards are called in creation order, whenever a navigation request is triggered. Guards may be resolved asynchronously, and the navigation is considered pending before all hooks have been resolved.

Every guard function receives three arguments:

  • to: Route: the target Route Object being navigated to.
  • from: Route: the current route being navigated away from.
  • next: Function: this function must be called to resolve the hook.

What action needs to be taken depends on the arguments provided to the next() function

  • next(): move on to the next hook in the pipeline. If no hooks are left, the navigation is confirmed.
  • next(false): abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.
  • next('/') or next({ path: '/' }): redirect to a different location. The current navigation will be aborted and a new one will be started. You can pass any location object to next, which allows you to specify options like replace: truename: 'home' and any option used in router-link‘s to prop or router.push
  • next(error): (2.4.0+) if the argument passed to next is an instance of Error, the navigation will be aborted and the error will be passed to callbacks registered via router.onError().

Eloquent JavaScript, 3rd Edition

A Modern Introduction to Programming

Marijn Haverbeke

Reflects the current state of JavaScript

Buy Now Read Review

Navigation Guard with Firebase Authentication

In our application we want to implement a global navigation guard in order to protect some views to ensure users login to the application to access them.

We will build on the functionality developed in How to use Firebase Authentication with Vue in GitHub repository this can be found in the Guards Branch


https://github.com/threenine/sourcelink-web
0 forks.
0 stars.
0 open issues.
Recent commits:

Information

This post assumes you have implemented Firebase Authentication continuing on from the configuration discussed How to Install Firebase with Vue.JS

If you have generated your Vue Project making use of the Vue CLI your project will already contain a router.js file which is essentially the implementation of the Vuex-Router which is a central repository to store all your applications routes.

We are going to edit this file slightly to add our Global Navigation Guard.

The first thing we are going to add is an additional Meta information to some of the routes in our application to signify that there are some routes which we would like to ensure only authenticated users can access.

In our simple project, thus far we are only going to have 2 routes, that being a Dashboard Page and the Users Profile page.

So we are going to edit each of these routes and Add an additional Meta Attribute to them to indicate that the route requires authentication to be accessed as follows:

JS

Our complete route listing will now appear as follows:

JS

Any routes you wish to add authentication too, you should add this additional attribute.

We can now add our Guard clause to our Router, which basically checks to see if the route it has been instructed to activate contains the requiresAuth attribute, and if it does it will check to see if the User is logged in, if they are then it will simply redirect them to the route if not it will redirect them to the login page.

If the route does not require authentication the user is simply redirected.

JS

Your complete router.js file will now appear as follows:

JS

If you run your application and try to access any of the routes that have been defined with the requiresAuth without logging in, you will be redirected to the login page.

Summary

We have now successfully and easily implemented a global navigation guard to our application, to help provide some protection to our restricted pages.

Gary Woodfine

Technical Director at Denizon
Gary is Technical Director at Denizon, an independent software vendor specialising in IoT, Field Service and associated managed services,enabling customers to be efficient, productive, secure and scalable in a way which helps them address and reduce their ecological impact.

Denizon's product line successfully integrate IoT, Artificial Intelligence and Blockchain technology to enable efficient, productive, secure and scalable solutions to help organisations address increasing energy demands, ecological impact and Health & Safety concerns of their staff.

Latest posts by Gary Woodfine (see all)

Tags: