VueJS: Redirect Unmatched Routes To 404

in VueJS Router

Like any other website if the router can not find the URL you're navigating to then you need to display a 404 page to your user for them to know this page doesn't exist anymore.

You can redirect any unmatched route to a 404 page in Vue by add the following code snippet to the bottom of your route object.

{ path: '*', component: require('./views/404.vue') }

This will match on all URLs, and display the component for a 404.vue component. This is important that it goes at the bottom of your defined routes, as Vue will go through your URLs and display the first matched component. Therefore placing this at the bottom of the routes object will catch everything that doesn't match a route of your application.

This is important to understand when defining dynamic routes for your application too, for example if you have 2 routes like the following.

const router = new VueRouter({
  routes: [
    { path: '/blog/:postname', component: Blog },
    { path: '/blog/contact', component: Contact },
  ]
})

If you were to navigate to /blog/contact URL you would think it will display the Contact component but it will actually display the Blog component with a route.params.postname of contact. Therefore you need to move static URL to the top of the list to make sure these are matched first.

const router = new VueRouter({
  routes: [
    { path: '/blog/contact', component: Contact },
    { path: '/blog/:postname', component: Blog },
  ]
})

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