9 April, 2018 Tags: ,

Vue.js: Handling undefined routes with vue-router

This is a very quick article / tip to show you guys a good approach to handle undefined routes, after all, you can ever trust on what your user will type in the url bar :).

So, in a typical Vue application you’ll have multiples routes for different components defined like this:

import Vue from 'vue';
import Home from '@/components/Home';
import Login from '@/components/Login';
import Clients from '@/components/Clients';

export default new Router({
  routes: [
    { path: '/', name: 'Home', component: Home },
    { path: '/login', name: 'Login', component: Login },
    { path: '/clients', name: 'Clients', component: Clients },
  ]
});

There’s nothing wrong with the code above, but if the user tries to access a route that was not previously defined like localhost:8080/#/cars¬†your application would show a blank page, and I am pretty sure that this is not the kind of behavior that you would want. So to prevent this we need to handle all the undefined routes by redirecting to a specific route after we set every possible routes for our application. In the end of routes array, add a new line with the path set to *:

export default new Router({
  routes: [
    { path: '/', name: 'Home', component: Home },
    { path: '/login', name: 'Login', component: Login },
    { path: '/clients', name: 'Clients', component: Clients },
    { path: '*', redirect: '/' },
  ]
});

So this slight modification will catch every possible routes that was not previously defined and will redirect to home route / thanks to path:’*’. If you want to, you can create a custom component to show the 404 message to your users.

Thank you, I hope this tutorial helps you to build better web applications. If you have a another approach on handling undefined routes with Vuejs and vue-routes let me know in the comments.

OTHER ARTICLES