VueJS: Route Meta Data

in VueJS Router

You can add additional information to a specific route by giving it route meta data, this meta data can then be picked up by the router on the beforeEach() function so you can add additional code when setting up your routes.

A good example of using the route meta data is to add a meta to certain routes that require authentication.

To add meta information to a certain route it's very simple all you need to do is add a new meta property to the route object.

const routes = [
    {
        path: '/',
        component: Home
    },
    {
        path: '/about',
        component: About,
        meta: { requiresAuth: true }
    },
    {
        path: '/contact',
        component: Contact
    }
];

As you can see the about page now has a requiresAuth meta property so we've defined this route as needing authentication we can now create a beforeEach function to check for this meta property and make changes to the router.

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.loggedIn()) {
      next({
        path: '/login'
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

This function will run before every route change and will check to see if the record has a requiresAuth property. If it doesn't have this property then we call the next() function to continue with the router.

If the route object has a meta requiresAuth then we can do checks to see if the user is authenicated in your app, if they're not then we redirect to the /login URL to authenticate the user, but if they're logged in then we can simply call the next() function.

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