VueJS: Vue Router Restricting Routes

in VueJS Router

In the previous examples of using the Vue Router we learnt how to build routes and how we can navigate around the application to view the previous examples please see them here.

VueJS Router

This information allows us to build an website but if we want to build an application where users need to login to see a page then we need to be able to restrict access to certain routes. In this tutorial we're going to go through examples of how we can restrict access to certain routes.

To restrict access you'll need to intercept the router and check to see if the user has access to the page if they do then it's ok to continue with the routing else we can redirect the user to another location.

There are two ways you can add restrictions to the routes, they can either be global settings so every route uses the same function or you can assign them on certain routes, therefore blocking on one route.

Globally

To perform on a check on URL you need to use the function router.beforeEach which is called before each change of the of the route. This function will pass in 3 arguments to, from and next.

To is the route where you're navigating to.

From is the route where you're coming away from.

Next a function that is the callback for the beforeEach function. Therefore every beforeEach function must end in a next() function as you're telling Vue Router what to do next, either continue with the current request, reject the request or redirect to another URL.

router.beforeEach((to, from, next) => {
  // ...
  next();
})

Single Route

If you want to add a beforeEach only for a single route then you can add a function to the route object.

const routes = [
    {
        path: '/',
        component: Home,
        beforeEnter: function(to, from, next){
            next('/home2')
        }
    }
]

This will redirect all routes to / to /home2

Authenticated User Access

If you want to block access to your on all routes unless the user is authenticated then you can do so by using the beforeEach function.

router.beforeEach((to, from, next) => {
    if (!Auth.loggedIn()) {
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    } else {
        next()
    }
});

View the demo to see this in action, you'll only be able to access the About page.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email