Blog>
Snippets

Pre-fetching Data with Navigation Guards

Example of fetching data before navigating to a route using Vue Router’s beforeEnter navigation guard, reducing the perceived loading time.
const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      component: UserComponent,
      beforeEnter: (to, from, next) => {
        // Fetch user data before entering the route
        getUserData(to.params.userId)
          .then(data => {
            // Pass the fetched data to the route's component via props
            to.params.userData = data;
            next();
          })
          .catch(error => {
            if (error.response && error.response.status == 404) {
              // Handle 404 error by redirecting to not-found route or display message
              next({ name: 'NotFound' });
            } else {
              // Handle other errors
              next(false);
            }
          });
      }
    },
  ]
});
A VueRouter instance is created with a route that has a beforeEnter guard. The guard fetches user data based on the userId route parameter before navigating to the UserComponent route. If data is successfully fetched, it is passed to the component via route params, and the navigation proceeds. If a 404 error is encountered, navigation redirects to a 'NotFound' route. For other errors, navigation is cancelled.